Nee*_*esh 20 iphone uinavigationcontroller uinavigationitem ios
我有一个导航栏,每侧都有左右两个按钮.我有一个customTitlelabel
我设置为titleView的UINavigationItem
.
[self.navigationItem setTitleView:customTitleLabel];
一切都很好.问题是,rightbarButton的大小是动态的,基于我在其中一个文本字段中得到的输入.
因此,标题会根据按钮之间的可用空间自动居中.
如何将标题设置为固定位置?
fol*_*ben 28
设置导航栏的titleView属性可以正常工作 - 无需子类化或更改自定义视图以外的任何帧.
让它相对于UINavigationBar的整体宽度居中的技巧是:
下面是一些示例代码,它创建一个带有标签的自定义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;
Run Code Online (Sandbox Code Playgroud)
occ*_*lus 15
你不能直接做你想做的事情 - 你的标题视图的位置是你无法控制的(当你管理时UINavigationBar
).
但是,至少有两种策略可以达到您想要的效果:
1)添加标题视图不是导航栏的"正确"标题视图,而是作为的子视图UINavigationBar
.(注意:这不是'正式'批准,但我已经看到它完成了,并且工作.显然你必须注意你的标题标签覆盖按钮的位,并处理不同方向的不同尺寸的导航条等. - 有点繁琐.)
2)创建一个智能UIView子类,在一个计算的位置显示一个给定的子视图(可能是你的UILabel),以有效地显示完全居中在屏幕上的子视图.为此,您的智能UIView子类将frame
通过更改frame
标签子视图的position()来响应布局事件(或属性更改等).
就个人而言,我喜欢方法2)最好的想法.
neo*_*eye 12
override func viewDidLoad() {
super.viewDidLoad()
navigationController?.navigationBar.topItem?.title = ""
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
navigationItem.title = "Make peace soon"
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
26981 次 |
最近记录: |