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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27296372/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 06:18:56  来源:igfitidea点击:

How to place UILabel in the center of navigation bar

iosxcodeuibuttoninterface-builderuilabel

提问by FrozenHeart

How to place UILabelin the center of navigation bar in XCode 6? Is it possible at all? I can place here, for example, UIButton, but unable to place UILabel. If no, what can I do then? Place a UIButtonwith the appropriate text and make it non-clickable?

如何UILabel在 XCode 6 中放置在导航栏的中心?有可能吗?例如,我可以在这里放置UIButton,但无法放置UILabel。如果没有,那我该怎么办?将 aUIButton与适当的文本一起放置并使其不可点击?

Thanks in advance.

提前致谢。

回答by darren102

In Xcode 6if you want to put a label inside the UINavigationBarfirstly you have to put a UIView there then put the UILabel inside the UIView (this is from the Storyboard btw).

Xcode 6如果你想要把一个标签内UINavigationBar首先你必须把一个UIView有然后把里面的UIView中的UILabel(这是从故事板BTW)。

If you do not put the UIViewfirst then the UILabelwill never get put onto the UINavigationBar.

如果您不放第UIView一个,UILabel则永远不会放上UINavigationBar.

回答by Ersin Sezgin

Create a UIView and add UILabelas 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.

注意:不要忘记设置您自己的帧值以获得更好的结果。

回答by Murat Yasar

Just make sure you try viewWillLayoutSubviewsmethod instead of viewDidLoadthat was what worked for me. Cheers!

只要确保您尝试viewWillLayoutSubviews方法而不是viewDidLoad对我有用的方法。干杯!