我正在尝试将视图添加到 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!)
}
这出来了:
在这两种情况下,我的标签都覆盖导航栏的一部分 . 我该怎么解决这个问题?
6 回答
状态栏的高度为20.您在分配
y
标签时也应考虑状态栏 . 你的_683640应该是希望能帮助到你 . 快乐编码!!
斯威夫特4 .
使用
NSLayoutConstraint
尝试此代码 . newView将出现在NavigationBar
下navigationBar的框架为(0 20; 375 44),您可以将标签y位置设置为64 .
您没有使用导航栏计算状态栏的高度 . 它们共有64个,44个导航条和20个状态栏
替换它
同
导航栏和状态栏一起高度为64.使其成为y位置