UIBarButtonItemは、ツールバーやナビゲーションバーなどに表示するボタンを管理するクラスです。
ボタンの種類は多種にわたり用意されています。
もちろん自作のボタンを表示させることも可能です。

UIBarButtonItemの基本

// 生成例
UIBarButtonItem *btn = [[UIBarButtonItem alloc] initWithTitle:@"ぼたん" // ボタンタイトル名を指定
                                                                                style:<UIBarButtonItemStyleスタイル> // スタイルを指定(※下記表参照)
                                                                               target:self // デリゲートのターゲットを指定
                                                                               action:@selector(hoge)// ボタンが押されたときに呼ばれるメソッドを指定
                                  ];


// システムで用意されている画像を使った生成例
UIBarButtonItem *btn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:<UIBarButtonSystemItemスタイル> // スタイルを指定
                                                                                                    target:self // デリゲートのターゲットを指定
                                                                                                    action:@selector(hoge) // ボタンが押されたときに呼ばれるメソッドを指定
                                  ];

// システムで用意されている画像を使った生成例
UIBarButtonItem *btn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:<UIBarButtonSystemItemスタイル> // スタイルを指定
                                                                                                    target:self // デリゲートのターゲットを指定
                                                                                                    action:@selector(hoge) // ボタンが押されたときに呼ばれるメソッドを指定
                                  ];

主要なプロパティ

action
アイテムタップ時のアクションメソッドを指定

style
アイテムのスタイルを指定

target
アイテム選択時にアクションを起こすオブジェクトを指定

width
アイテムの横幅を指定

customView
アイテムを表すカスタムビューを指定

possibleTitles
バー上で表示するタイトルの配列を返す

主要なインスタンスメソッド

initWithBarButtonSystemItem:target:action:
指定されたスタイルのインスタンスを生成を行う
– (id)initWithBarButtonSystemItem:(BarButtonSystemItem)systemItem target:(id)target action:(SEL)action
例)UIBarButtonItem *btnitem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(hoge)];

initWithCustomView:
指定されたカスタムビューを使用し、インスタンスの生成を行う
  • (id)initWithCustomView:(UIView *)customView
例)UIBarButtonItem *btnitem = [[UIBarButtonItem alloc] initWithCustomView:customView];

initWithImage:style:target:action:
指定されたイメージ(画像)を使用し、インスタンスの作成を行う
  • (id)initWithImage:(UIImage *)image style:(UIBarButtonItemStyle)style target:(id)target action:(SEL)action
例)UIBarButtonItem *btnitem = [[UIBarButtonItem alloc] initWithImage:image style:UIBarButtonSystemItemDone target:self action:@selector(hoge)];

initWithTitle:style:target:action:
指定されたタイトルを使用し、インスタンスの生成を行う
  • (id)initWithTitle:(NSString *)title style:(UIBarButtonItemStyle)style target:(id)target action:(SEL)action
例)UIBarButtonItem *btnitem = [[UIBarButtonItem alloc] initWithTitle:@"たいとる" style:UIBarButtonSystemItemDone target:self action:@selector(hoge)];
最終更新:2013年07月26日 17:22