以下で宣言された UIToolBar ボタンがあります。
UIToolbar *toolbar = [[UIToolbar alloc] init];
toolbar.frame = CGRectMake(0.0, 0.0, self.view.frame.size.width, 64.0);
戻るボタンとして左側に追加される UIBarButtonItem もあります。しかし、中央揃えのラベル タイトルを UIToolbar に追加するにはどうすればよいでしょうか?
以下で宣言された UIToolBar ボタンがあります。
UIToolbar *toolbar = [[UIToolbar alloc] init];
toolbar.frame = CGRectMake(0.0, 0.0, self.view.frame.size.width, 64.0);
戻るボタンとして左側に追加される UIBarButtonItem もあります。しかし、中央揃えのラベル タイトルを UIToolbar に追加するにはどうすればよいでしょうか?
UILabel を作成し、ツールバーの項目として追加します。
UIBarButtonItem *toolBarTitle = [[UIBarButtonItem alloc] initWithCustomView:myLabel];
中央に配置する場合は、両側に柔軟なスペースを追加します。
UIBarButtonItem *flexible = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil]
UILabel *lblTitle = [[UILabel alloc] initWithFrame:CGRectMake(50, 50, 150, 20)];
lblTitle.backgroundColor = [UIColor clearColor];
lblTitle.textColor = [UIColor blackColor];
lblTitle.textAlignment = NSTextAlignmentLeft;
[self.view addSubview:lblTitle];
UIBarButtonItem *typeField = [[UIBarButtonItem alloc] initWithCustomView:lblTitle];
toolBar.items = [NSArray arrayWithArray:[NSArray arrayWithObjects:backButton,spaceBar,lblTitle, nil]];
これはあなたの問題を解決すると思います。
他の回答はどれも、私が望んでいたほどコピーして貼り付けることができなかったので...
UILabel *toolbarLabel = [[UILabel alloc] initWithFrame:CGRectZero];
toolbarLabel.text = @"Text in yo toolbar";
[toolbarLabel sizeToFit];
toolbarLabel.backgroundColor = [UIColor clearColor];
toolbarLabel.textColor = [UIColor grayColor];
toolbarLabel.textAlignment = NSTextAlignmentCenter;
UIBarButtonItem *labelItem = [[UIBarButtonItem alloc] initWithCustomView:toolbarLabel];
UIBarButtonItem *flexible = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
[self setToolbarItems:@[flexible, labelItem, flexible] animated:false];
これは、ナビゲーション コントローラーを介してツールバーが表示されていることを前提としています (ナビゲーション コントローラーによって表示される任意のビュー コントローラーから表示するため[self.navigationController setToolbarHidden:NO animated:YES];
) 。
UIToolbarには title プロパティがありません。他の人が示唆したように、タイトルとしてUILabelを追加する必要があります。
または、代わりにUINavigationBarを使用して初期化することもできます- (id)initWithTitle:(NSString *)title;