简体   繁体   English

如何将UILabel放置在导航栏的中心

[英]How to place UILabel in the center of navigation bar

How to place UILabel in the center of navigation bar in XCode 6? 如何将UILabel放置在XCode 6的导航栏中心? Is it possible at all? 有可能吗? I can place here, for example, UIButton , but unable to place UILabel . 我可以放在这里,例如, UIButton ,但无法放置UILabel If no, what can I do then? 如果不是,我该怎么办? Place a UIButton with the appropriate text and make it non-clickable? 放置一个带有适当文本的UIButton并使其不可点击?

Thanks in advance. 提前致谢。

In Xcode 6 if you want to put a label inside the UINavigationBar firstly you have to put a UIView there then put the UILabel inside the UIView (this is from the Storyboard btw). Xcode 6如果你想在UINavigationBar放置一个标签,你必须在那里放一个UIView然后把UILabel放在UIView里面(这是来自故事板btw)。

If you do not put the UIView first then the UILabel will never get put onto the UINavigationBar . 如果你没有先放置UIView那么UILabel永远不会被放到UINavigationBar

Create a UIView and add UILabel as it's subview and then set your NavigationItem 's titleView as previously created UIView. 创建一个UIView并添加UILabel作为它的子视图,然后将NavigationItem的titleView设置为先前创建的UIView。

UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 150, 40)];
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 150, 40)];
label.text = @"Hello";
label.textAlignment = NSTextAlignmentCenter;
[view addSubview:label];
self.navigationItem.titleView = view;

Note : Don't forget to set your own frame values to get better result. 注意 :不要忘记设置自己的帧值以获得更好的结果。

Just make sure you try viewWillLayoutSubviews method instead of viewDidLoad that was what worked for me. 只要确保你尝试viewWillLayoutSubviews方法而不是viewDidLoad ,这对我viewDidLoad Cheers! 干杯!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM