2011-10-10 1 views
14

私はiOS初心者です。クリックすると自分の機能を実行するナビゲーションバーボタンがあります。それをする最善の方法は何ですか?UIBarButtonItemにカスタムセレクタを追加する

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

答えて

42

一つの方法として、ターゲットとアクションとinitにある:

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

別の方法あなたが

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

、それを作成した後、ターゲットとアクションを設定することで、ターゲットはのインスタンスであります呼び出されるオブジェクトselfの場合、メソッドはオブジェクトのこのインスタンス上にあります。

アクションは、呼び出されるメソッドです。通常は、IBActionを使用してデザイナーにヒントを与えて、それがアクションであることをヒントします。それはvoidにコンパイルされます。

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

'[buttonHello setTarget:self];と' [buttonHello setAction:@selector(sayHello :)];ありがとうございました。 – Greg

+0

この美しく書かれた答え、ブライアンのおかげで、 Appleの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

これが役立つことを願っています!

関連する問題