UINavigationItem のタイトルを中央に配置する 質問する

UINavigationItem のタイトルを中央に配置する 質問する

両側に左バー ボタンと右バー ボタンの両方があるナビゲーション バーがあります。customTitlelabelの titleView として設定した がありますUINavigationItem

[self.navigationItem に TitleView を設定します:customTitleLabel];

今はすべて正常です。問題は、rightbarButton のサイズが、テキスト フィールドの 1 つで取得した入力に基づいて動的に変化するという点です。

したがって、ボタン間の使用可能なスペースに基づいて、タイトルは自動的に中央に配置されます。

タイトルを固定位置に設定するにはどうすればよいですか?

ベストアンサー1

ナビゲーション バーの titleView プロパティを設定すると問題なく動作します。カスタム ビュー以外のフレームをサブクラス化したり変更したりする必要はありません。

UINavigationBar の全体の幅に対して中央に配置するためのコツは次のとおりです。

  1. テキストのサイズに応じてビューの幅を設定します
  2. 配置を中央に設定し、
  3. 利用可能なスペースに合わせてサイズが変更されるように自動サイズ変更マスクを設定します

以下は、方向や左または右のバーボタンの幅に関係なく、UINavigationBar の中央に留まるラベルを持つカスタム titleView を作成するコード例です。

self.title = @"My Centered Nav Title";

// Init views with rects with height and y pos
CGFloat titleHeight = self.navigationController.navigationBar.frame.size.height;
UIView *titleView = [[UIView alloc] initWithFrame:CGRectZero];
UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectZero];

// Set font for sizing width
titleLabel.font = [UIFont boldSystemFontOfSize:20.f];

// Set the width of the views according to the text size
CGFloat desiredWidth = [self.title sizeWithFont:titleLabel.font
                            constrainedToSize:CGSizeMake([[UIScreen mainScreen] applicationFrame].size.width, titleLabel.frame.size.height)
                                lineBreakMode:UILineBreakModeCharacterWrap].width;

CGRect frame;

frame = titleLabel.frame;
frame.size.height = titleHeight;
frame.size.width = desiredWidth;
titleLabel.frame = frame;

frame = titleView.frame;
frame.size.height = titleHeight;
frame.size.width = desiredWidth;
titleView.frame = frame;

// Ensure text is on one line, centered and truncates if the bounds are restricted
titleLabel.numberOfLines = 1;
titleLabel.lineBreakMode = UILineBreakModeTailTruncation;
titleLabel.textAlignment = NSTextAlignmentCenter;

// Use autoresizing to restrict the bounds to the area that the titleview allows
titleView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin;
titleView.autoresizesSubviews = YES;
titleLabel.autoresizingMask = titleView.autoresizingMask;

// Set the text
titleLabel.text = self.title;

// Add as the nav bar's titleview
[titleView addSubview:titleLabel];
self.navigationItem.titleView = titleView;

おすすめ記事