在视图上自动布置导航栏标题

时间:2019-01-03 20:18:19

标签: ios swift uinavigationbar nslayoutconstraint

我有一个简单的类,它创建一个包含标签的UIView。我想将该视图用作UINavigationBar的中央部分,在两侧各有2个按钮。以下代码无需添加标签即可很好地运行:

class myView : UIView {
    override init(frame: CGRect) {
        super.init(frame: frame)

        self.backgroundColor = .green
    }
}

我这样叫课:

let avatar = UIBarButtonItem(image: avatarImage, ...)
let otherButton = UIBarButtonItem(image: otherImage, ...)

navigationItem.leftBarButtonItems  = [avatar]
navigationItem.rightBarButtonItems = [otherButton]

let headerTitle = myView(frame: .zero)
headerTitle.translatesAutoresizingMaskIntoConstraints = false
navigationItem.titleView = headerTitleView

但是如果我在UIView中添加标签:

class myView : UIView {
    override init(frame: CGRect) {
        super.init(frame: frame)

        self.backgroundColor = .green

        let theLabel = UILabel(frame: .zero)
        theLabel.text = "The Title"
        theLabel.textAlignment = .center
        theLabel.translatesAutoresizingMaskIntoConstraints = false

        self.addSubview(theLabel!)
    }
}

..我看到了标签,但是它被粘贴在视图的最左侧。如果我尝试向标签添加约束,则类似以下内容:

NSLayoutConstraint.activate([
    theLabel.centerXAnchor.constraint(equalTo: self.centerXAnchor),
    theLabel.centerYAnchor.constraint(equalTo: self.centerYAnchor)
])

..它崩溃,因为self(UIView)的大小仍然为零。

我尝试了layoutIfNeeded()sizeToFit()的各种组合,但到目前为止没有成功。如何将视图放置为导航栏的标题以及该视图内的布局元素?

1 个答案:

答案 0 :(得分:1)

我猜测是订单错误

self.addSubview(theLabel) // first
NSLayoutConstraint.activate([  // then second
  theLabel.centerXAnchor.constraint(equalTo: self.centerXAnchor),
  theLabel.centerYAnchor.constraint(equalTo: self.centerYAnchor)
])