2010-08-07 26 views
2

我正在使用兩個按鈕。我想訪問這兩個按鈕從兩個不同的對象function.-如何全局初始化目標C中的按鈕?

(id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { 
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) { 
     // Custom initialization 
     button1= [UIButton buttonWithType:UIButtonTypeRoundedRect] ; 
     button2= [UIButton buttonWithType:UIButtonTypeRoundedRect] ; 
     button1.frame = CGRectMake(50, 50, 100, 30); 
     button2.frame = CGRectMake(160, 50, 100, 30); 
    } 
    return self; 
} 

和我的函數是foo的()和bar()。 在這些函數中,我使用button1和button2。 但它不工作。

回答

1

首先,我會建議使用Interface Builder創建按鈕並將它們連接到控制器中的IBOutlet。然後,您可以定義訪問器方法,以允許您從控制器外部的函數/方法訪問這些按鈕(或使用@synthesize自動定義它們)。你要小心,不要打破封裝太多。你究竟想要用你的功能做什麼?

編輯:正如我在下面的評論中提到的,我現在已經找出了問題所在。你需要retain的按鈕,像這樣:

-(id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { 
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) { 
     // Custom initialization 
     button1= [[UIButton buttonWithType:UIButtonTypeRoundedRect] retain]; 
     button2= [[UIButton buttonWithType:UIButtonTypeRoundedRect] retain]; 
     button1.frame = CGRectMake(50, 50, 100, 30); 
     button2.frame = CGRectMake(160, 50, 100, 30); 
    } 
    return self; 
} 
+0

David,我不想使用Interface Builder。那麼,有沒有解決辦法? IS以上代碼是否正確初始化按鈕並在不同的功能中使用它們? – Tauquir 2010-08-07 09:18:08

+0

@Tauquir:您不必使用Interface Builder來遵循我的其他建議(儘管我確實推薦它)。你應該做的是什麼?你確定他們是功能而不是方法嗎? – David 2010-08-07 09:21:46

+0

@大衛:其實我通過點擊一個按鈕「CLick me」生成兩個按鈕。爲此,我在「loadView」中創建了「點擊我」按鈕。我再次調用一個「按下」功能來生成這兩個按鈕。然後在「按下」功能中創建第三個按鈕「交換」。現在,當我點擊這個「交換」按鈕,然後這些按鈕應該交換。 – Tauquir 2010-08-07 09:30:18