我希望我的导航栏在中间显示两件事。其中之一是列表名称,另一个是用户名称。用户名将放置在列表名称下。到目前为止我所做的是,我以编程方式创建了两个标签和一个超级视图,并设置titleView
of navigationItem
.
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
The thing is, I'm picking width randomly, which leads to alignment problems in different devices. How to achieve middle alignment in my case?
![iphone 6](https://i.stack.imgur.com/JBuGq.png)
方法:
-
titleView
始终居中
- 因此,将自定义视图的宽度设置为与
navigationBar
(宽度-40)
Code
private func setupNavigationItems() {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.text = "aaaaa"
label.backgroundColor = .green
label.textAlignment = .left
navigationItem.titleView = label
if let navigationBar = navigationController?.navigationBar {
label.widthAnchor.constraint(equalTo: navigationBar.widthAnchor, constant: -40).isActive = true
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)