我正在尝试创建自定义titleView并将位置更改为后退按钮的旁边。
titleView应如下所示:
所以我做的是:
private func setupNavigationItems() {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.text = "Info"
label.textColor = UIColor.black
label.textAlignment = .left
navigationItem.titleView = label
if let navigationBar = navigationController?.navigationBar {
label.widthAnchor.constraint(equalTo: navigationBar.widthAnchor, constant: -40).isActive = true
}
self.navigationController?.navigationBar.tintColor = UIColor.black
}
override func updateViewConstraints() {
super.updateViewConstraints()
setupNavigationItems()
}
它有效,但在某些情况下我会崩溃:
***因未捕获的异常'NSGenericException'而终止应用, 原因:'无法使用锚点激活约束 和 因为他们没有共同点 祖先。约束或其锚点是否引用了项目 不同的视图层次结构?这是非法的。'
如何修复此崩溃?有更好的方法来更改导航标题的位置吗?
由于
答案 0 :(得分:1)
要获得想要使用的效果,
navigationItem.backBarButtonItem
而不是:
navigationItem.titleView
backBarButtonItem将自动显示您以前的viewcontroller的标题,但可以将其修改为您喜欢的任何内容,如下所示:
答案 1 :(得分:0)
替换此代码: -
label.widthAnchor.constraint(equalTo: navigationBar.widthAnchor, multiplier: 0.8).isActive = true
使用此代码: -
let lbl = UILabel(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width * 0.8, height: 44))
lbl.text = "Info"
lbl.textColor = .black
lbl.textAlignment = .left
navigationItem.titleView = lbl
根据您的需要更改乘数。
或强>
无约束地设置UILabel的帧。
extension ConnectableObservableType {
func autoconnect() -> Observable<E> {
return Observable.create { observer in
return self.do(onSubscribe: {
_ = self.connect()
}).subscribe { (event: Event<Self.E>) in
switch event {
case .next(let value):
observer.on(.next(value))
case .error(let error):
observer.on(.error(error))
case .completed:
observer.on(.completed)
}
}
}
}
}