xyk blog

最近は iOS 開発の記事が多めです。

ツールバーを追加する方法

環境:iOS SDK 7.1

f:id:xyk:20140911150859p:plain

1. UINavigationController 管理下の場合

UINavigationController を使っている場合はすでにツールバーが組み込まれている。
デフォルトだと非表示となっているので以下のように ツールバーを表示したい UIViewController のviewDidLoadメソッド等でtoolbarHiddenプロパティを NO にすればよい。

self.navigationController.toolbarHidden = NO;
// or
// [self.navigationController setToolbarHidden:NO animated:NO];

このツールバーにボタンを追加するには、UIBarButtonItemオブジェクトを作成し、UIViewController のtoolbarItemsプロパティにセットするか、setToolbarItems:animated:メソッドを使う。

// ボタン作成
UIBarButtonItem *btn1 = [[UIBarButtonItem alloc] initWithTitle:@"ボタン"
                                                         style:UIBarButtonItemStylePlain
                                                        target:nil
                                                        action:nil];

// ボタン追加
self.toolbarItems = @[btn1];
// or
// [self setToolbarItems:@[btn1] animated:NO];

2. UIToolbar でツールバーを作る

自分で UIToolbar オブジェクトを作成し、UIVeiw にaddSubviewすればよい。
以下では画面下に表示するようにしている。

UIToolbar *toolBar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, self.view.bounds.size.height - 44, self.view.bounds.size.width, 44)];
[self.view addSubview:toolBar];

このツールバーにボタンを追加するには、UIBarButtonItemオブジェクトを作成し、UIViewController のtoolbarItemsプロパティにセットするか、setToolbarItems:animated:メソッドを使う。

// ツールバー作成、ビュー追加
UIToolbar *toolBar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, self.view.bounds.size.height - 44, self.view.bounds.size.width, 44)];
[self.view addSubview:toolBar];

// ボタン作成
UIBarButtonItem *btn1 = [[UIBarButtonItem alloc] initWithTitle:@"ボタン"
                                                         style:UIBarButtonItemStylePlain
                                                        target:nil
                                                        action:nil];

// ボタン追加
toolBar.items = @[btn1];
// or
// [toolBar setItems:@[btn1] animated:NO];