设置自定义视图左对齐。
将自定义视图设置为leftBarButtonItem并不方便,因为我们会遇到返回按钮的问题。
将自定义视图设置为navigationBar的子视图并不方便,因为:
- 当设置了右键时,我们无法轻松控制自定义视图的宽度。我们可以得到重叠的自定义视图和右键
- 我们需要添加自定义 navTitleView 并在每个 viewWillAppear 和 viewWillDissapear 中删除它。这是额外的,不是干净的代码。
所以?
我刚刚为 customTitleView 添加了宽度约束。
CustomTitleView 类内部:
private func layoutViewsConfig() {
// Width constraint needed to align view to left
let widthConstraint = NSLayoutConstraint.init(item: self, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: UIScreen.main.bounds.width)
widthConstraint.priority = .init(748)
let heightConstraint = NSLayoutConstraint.init(item: self, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 50)
self.addConstraint(widthConstraint)
self.addConstraint(heightConstraint)
}
然后,在您的 ViewController 内部:
var navigationTitleView = NavigationSubtitleView()
self.navigationItem.titleView = navigationTitleView
我们有: