【发布时间】:2017-07-07 09:05:24
【问题描述】:
我正在尝试向UINavigationController 添加一个视图,其顶部与导航栏的底部对齐。
我尝试通过将以下内容添加到我的 UINavigationController 子类来使用约束:
override func viewDidAppear(_ animated: Bool) {
self.label = UILabel()
self.label?.translatesAutoresizingMaskIntoConstraints = false
self.label?.backgroundColor = UIColor.red
self.label?.text = "label text"
self.view.addSubview(self.label!)
let horConstraint = NSLayoutConstraint(item: label!, attribute: .top, relatedBy: .equal,
toItem: topLayoutGuide, attribute: .bottom,
multiplier: 1.0, constant: 0.0)
let widthConstr = NSLayoutConstraint(item: label!, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 100)
let heightConstr = NSLayoutConstraint(item: label!, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 100)
view.addConstraints([horConstraint, widthConstr, heightConstr])
}
结果如下:
我尝试设置子视图的框架:
override func viewDidAppear(_ animated: Bool) {
self.label = UILabel(frame: CGRect(x: 0, y: navigationBar.frame.height, width: 300, height: 100))
self.label?.translatesAutoresizingMaskIntoConstraints = false
self.label?.backgroundColor = UIColor.red
self.label?.text = "label text"
self.view.addSubview(self.label!)
}
结果出来了:
在这两种情况下,我的标签都覆盖了导航栏的一部分。我该如何解决这个问题?
【问题讨论】:
-
尝试给 y 位置 64