【发布时间】:2015-07-05 00:10:24
【问题描述】:
我希望我的导航栏在中间显示两件事。其中一个是列表名称,另一个是用户名。用户名将放在列表名称下。到目前为止我所做的是,我以编程方式创建了两个标签和一个超级视图,并设置了navigationItem 的titleView。
override func viewDidLoad() {
super.viewDidLoad()
var rectForView = CGRect(x: 0, y: 0, width: 190, height: 176)
var viewForTitle = UIView(frame: rectForView)
var rectForNameLabel = CGRect(x: 0, y: 63, width: 190, height: 30)
var listNameLabel = UILabel(frame: rectForNameLabel)
listNameLabel.text = "Name of the List...."
listNameLabel.textAlignment = NSTextAlignment.Center
listNameLabel.font = UIFont(name: "HelveticaNeue-Bold", size: 15)
var rectForListLabel = CGRect(x: 0, y: 93, width: 190, height: 20)
var usersOfListLabel = UILabel(frame: rectForListLabel)
usersOfListLabel.text = "some Users...."
usersOfListLabel.textAlignment = NSTextAlignment.Center
usersOfListLabel.font = UIFont(name: "HelveticaNeue", size: 10)
viewForTitle.addSubview(listNameLabel)
viewForTitle.addSubview(usersOfListLabel)
self.navigationItem.titleView = viewForTitle
问题是,我随机选择宽度,这会导致不同设备出现对齐问题。在我的情况下如何实现中间对齐?
【问题讨论】:
-
您是否尝试为 CenterX 设置 NSLayoutConstraint?
-
我没有。但我试图将“textForViews”中心x变量设置为视图(控制器附带)中心x变量
-
顺便说一下如何以编程方式添加约束?
-
在 viewDidload 中尝试了一个: var constX = NSLayoutConstraint(item: viewForTitle, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant : 0) viewForTitle.addConstraint(constX) ........ 但是没用。程序崩溃。它说“视图层次结构没有为约束做好准备:
-
在添加为子视图后激活约束?
标签: ios iphone swift alignment uinavigationitem