[iOS]UINavigationBarのカスタマイズ

iOSアプリのデザインをInterfaceBuilder上で作成したあと、
パーツ[UINavigationBar]のボタンをカスタマイズしようとしたら
意外とハマったので一応メモします。

やりたかったことは下記のとおりです。
①InterfaceBuilderでデザインを作成
②別のクラス[UIViewController]で①のデザインを流用
③ヘッダのボタン等を変更
(別にそれ用のデザインを作ってもよかったのですが・・・)

サンプルコード

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
    	# No.01
		UINavigationBar *_navBar = ( UINavigationBar * )[self.view viewWithTag:10];

    	# No.02
		UIBarButtonItem *_leftBtn	= [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(tapBarBtn:)];
		UIBarButtonItem *_rightBtn	= [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(tapBarBtn:)];
		
    	# No.03
		_navBar.topItem.leftBarButtonItem	= _leftBtn;
		_navBar.topItem.rightBarButtonItem	= _rightBtn;
    }
    return self;
}
# No.01
InterfaceBuilder上で配置したパーツ[UINavigationBar]の
インスタンスを生成する

# No.02
表示したいボタンのインスタンスを定義する
(対象のアクションは適当です)

# No.03
No.01で生成したインスタンスの変数[topItem]に対して
左右のボタンを管理するそれぞれの変数[leftBarButtonItem]と
[rightBarButtonItem]に代入する


コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です

日本語が含まれない投稿は無視されますのでご注意ください。(スパム対策)