我有自定义UINavigationBar
:
class NavBar: UINavigationBar {
override init(frame: CGRect) {
super.init(frame: frame)
self.commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.commonInit()
}
private func commonInit() {
self.barTintColor = .orange
}
override func sizeThatFits(_ size: CGSize) -> CGSize {
return CGSize(width: UIScreen.main.bounds.width, height: 66)
}
}
当我设置titleView
和/或barButtonItems
时,它们不是垂直居中的:
class ViewController : UIViewController {
override func viewDidLoad() {
self.viewDidLoad()
self.edgesForExtendedLayout = []
let searchField = UITextField(frame: CGRect(x: 0, y: 0, width: 100, height: 44))
searchField.backgroundColor = .green
self.navigationItem.titleView = searchField
}
}
结果:
如何垂直居中textView
& barButtonItems
在UINavigationBar
内,当它的高度不是默认值时?
我已尝试设置textView
bounds
,frame
- 无效。
使用:
let view = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 44))
view.backgroundColor = .green
let searchField = UITextField(frame: CGRect(x: 0, y: -20, width: 100, height: 44))
searchField.backgroundColor = .red
view.addSubview(searchField)
self.navigationItem.titleView = view
我可以改变searchField
的位置,但似乎我做错了。
我可以以某种方式设置UINavigationBar
'填充' /'保证金'或textView
& barButtonItem
课程中的offset
NavBar
?
答案 0 :(得分:1)
你现在基本上是在攻击UINavigationBar,这就是为什么我不能期待它的稳定行为。 Apple正在劝阻你这样做。即使在Apple example of extended UINavBar中,他们只是添加了另一个视图,并在条形图和视图之间无缝转换。你也可以尝试
setTitleVerticalPositionAdjustment(_:for:)
方法,但我相信它只影响标题而不影响标签栏项目。我会使用苹果解决方案来避免意外问题或创建自定义导航栏而无需继承UINavBar。