8

以下で宣言された UIToolBar ボタンがあります。

UIToolbar *toolbar = [[UIToolbar alloc] init];
toolbar.frame = CGRectMake(0.0, 0.0, self.view.frame.size.width, 64.0);

戻るボタンとして左側に追加される UIBarButtonItem もあります。しかし、中央揃えのラベル タイトルを UIToolbar に追加するにはどうすればよいでしょうか?

4

6 に答える 6

7

UILabel を作成し、ツールバーの項目として追加します。

UIBarButtonItem *toolBarTitle = [[UIBarButtonItem alloc] initWithCustomView:myLabel];

中央に配置する場合は、両側に柔軟なスペースを追加します。

UIBarButtonItem *flexible = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil]
于 2013-10-21T08:21:02.883 に答える
7
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]];

これはあなたの問題を解決すると思います。

于 2013-10-21T08:21:18.467 に答える
4

他の回答はどれも、私が望んでいたほどコピーして貼り付けることができなかったので...

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];) 。

次のようになります (iOS 9): カスタム ビューを持つ UIBarButtonItem の UILabel

于 2016-01-26T21:33:23.560 に答える
1

UIToolbarには title プロパティがありません。他の人が示唆したように、タイトルとしてUILabelを追加する必要があります。

または、代わりにUINavigationBarを使用して初期化することもできます- (id)initWithTitle:(NSString *)title;

于 2013-10-21T08:26:15.397 に答える