本文介绍了如何以编程方式在导航栏下方添加视图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图将视图添加到UINavigationController
,其顶部与导航栏的底部对齐.
I'm trying to add a view to a UINavigationController
with its top aligned with the navigation bar's bottom.
我尝试通过将以下内容添加到我的UINavigationController
子类中来使用约束:
I tried using constraints by adding the following to my UINavigationController
subclass:
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])
}
结果如下:
然后我尝试通过设置子视图的框架:
And I tried by setting the frame of my subview:
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!)
}
这出来了:
在两种情况下,我的标签都覆盖了导航栏的一部分.我该如何解决?
In both cases my label covers part of the navigation bar. How to I fix this?
推荐答案
状态栏的高度为20.分配标签的y
时,还应考虑状态栏.您的viewDidAppear
应该是
Height of status bar is 20.You should consider status bar also while assigning y
of your label. Your viewDidAppear
should be
override func viewDidAppear(_ animated: Bool) {
self.label = UILabel(frame: CGRect(x: 0, y: navigationBar.frame.height+20, width: navigationBar.frame.width, height: 100))
self.label?.translatesAutoresizingMaskIntoConstraints = false
self.label?.backgroundColor = UIColor.red
self.label?.text = "label text"
self.view.addSubview(self.label!)
}
希望它会有所帮助.祝您编码愉快!
Hope it helps. Happy Coding!!
这篇关于如何以编程方式在导航栏下方添加视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!