2011-09-24 12 views
0

我有一個方法,需要一個UIButton,修改它的屬性並返回一個UIButton。但是,它似乎沒有被初始化。我確信我在這裏做了內存管理方面的錯誤,但並不知道如何解決這個問題。沒有發生運行時錯誤。在方法中返回自定義的UIButton?

它被稱爲是這樣的...

newGameBtn = [self customButtonFromButton:newGameBtn 
           withText:[NSString stringWithFormat:@"NEW GAME"] 
          withFontSize:22 
          withBorderColor:[UIColor orangeColor] 
           isSilent:YES]; 
[dashboardContainer addSubview:newGameBtn]; 

的方法定義如下......

- (UIButton*) customButtonFromButton:(UIButton*)button withText:(NSString*)text withFontSize:(int)fontSize withBorderColor:(UIColor*)borderColor isSilent:(BOOL)isSilent { 
    button = [[[UIButton alloc] init] autorelease]; 

    // Set properties from parameters 
    // Other conditional custom stuff here 

    return button; 
} 

注:newGameBtn是類型的UIButton的*,並與初始化: newGameBtn = [[UIButton buttonWithType:UIButtonTypeCustom] retain];

另一個選擇可能是子類UIButton,但我想我會嘗試解決這個問題,因爲我已經走過了這條路。

回答

2

的第一行創建按鈕的時候能得到正確初始化按鈕,您應該使用+[UIButton buttonWithType:]

大多數類未通過默認的-[NSObject init]方法正確初始化。因此,請查看類引用或超類引用,以獲取可用的初始化方法。

在這種情況下,您還應該設置一個frame

+0

+1。工廠方法是獲得正確配置的按鈕的*唯一*方法。使用任何init方法都依賴於當前可能會隨時改變的實現。沒辦法設置按鈕類型,例如 - 這是一個重要的屬性。這就是爲什麼子類化也不合適的原因。 – Eiko

+0

啊,在重構中,我忘了移動被摧毀的框架。是的。那樣做了。請注意,在我對@Martin Ullrich的回覆中,我實際上是在使用buttonWithType:init。 –

1

你不用你的方法修改這個按鈕,你正在用alloc-init創建一個全新的按鈕!

如果你想改變你的第一個參數的按鈕即可刪除您的方法

+0

我確實嘗試過,但仍然沒有活動按鈕。我也試過newGameBtn = [[UIButton buttonWithType:UIButtonTypeCustom] retain];在將newGameBtn傳遞給方法之前,它也不會呈現任何東西。 –

+0

我也試過newGameBtn = [[[[UIButton alloc] init] retain];在調用該方法之前,這也沒有奏效。 –

+0

你是否正確設置了它的'frame'屬性? –