2011-10-10 100 views
14

我是一個iOS新手。我有一個導航欄按鈕,點擊時應執行我自己的功能。什麼是最好的方式來做到這一點?添加自定義選擇器到UIBarButtonItem

UIBarButtonItem *doneBarButtonItem=[[UIBarButtonItem alloc] init]; 
[email protected]"Done"; 
self.navigationItem.rightBarButtonItem = doneBarButtonItem; 
[doneBarButtonItem release]; 

回答

42

一種方式是與目標和行動初始化:

UIBarButtonItem *buttonHello = [[UIBarButtonItem alloc] initWithTitle:@"Say Hello"  
    style:UIBarButtonItemStyleBordered target:self action:@selector(sayHello:)]; 

另一種方式是設定目標和行動,你創造了它

[buttonHello setTarget:self]; 
[buttonHello setAction:@selector(sayHello:)]; 

目標後的實例該對象將被調用。在自我的情況下,該方法將在該對象的這個實例上。

動作是將被調用的方法。通常情況下,你用IBAction裝飾它以向設計者暗示它是一個動作。它編譯爲無效。

- (IBAction)sayHello:(id)sender 
{ 
    // code here 
} 
+0

謝謝''buttonHello setTarget:self];''和'[buttonHello setAction:@selector(sayHello :)];'....這救了我! – Greg

+0

感謝這封美麗的答案,Bryan;你有沒有機會以這種方式重寫蘋果的其他API文檔? ;-) – Slowburner

2

有多種,你可以使用不同的init調用,在實例方法部分這裏列出:

http://developer.apple.com/library/ios/#documentation/uikit/reference/UIBarButtonItem_Class/Reference/Reference.html

- (id)initWithBarButtonSystemItem:(UIBarButtonSystemItem)systemItem target:(id)target action:(SEL)action 
- (id)initWithCustomView:(UIView *)customView 
- (id)initWithImage:(UIImage *)image style:(UIBarButtonItemStyle)style target:(id)target action:(SEL)action 
- (id)initWithTitle:(NSString *)title style:(UIBarButtonItemStyle)style target:(id)target action:(SEL)action 

此外,您還可以在這裏檢查出使用中的一個樣本:

How to set target and action for UIBarButtonItem at runtime

希望這有助於!

相關問題