gpt4 book ai didi

iphone - UINavigationItem 居中标题

转载 作者:IT王子 更新时间:2023-10-29 08:04:32 29 4
gpt4 key购买 nike

我有一个 navigationBar,每侧都有左栏和右栏按钮。我有一个 customTitlelabel,我将其设置为 UINavigationItem 的 titleView。

[self.navigationItem setTitleView:customTitleLabel];

现在一切都很好。问题是,rightbarButton 的大小是动态的,具体取决于我在其中一个文本字段中获得的输入。

因此,标题会根据按钮之间的可用空间自动居中。

如何将标题设置到固定位置?

最佳答案

设置导航栏的 titleView 属性效果很好 - 除了自定义 View 之外,无需子类化或更改任何框架。

让它相对于 UINavigationBar 的整体宽度居中的技巧是:

  1. 根据文本的大小设置 View 的宽度
  2. 将对齐方式设置为居中
  3. 设置 autoresizingmask 使其调整到可用空间

下面是一些示例代码,它创建了一个带有标签的自定义 titleView,该标签​​在 UINavigationBar 中保持居中,而不管方向、左侧或右侧栏按钮的宽度如何:

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;

关于iphone - UINavigationItem 居中标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8258879/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com