0

我有一个包含标签的简单 UIView 子类。该子类具有以下 init 方法:

override init(frame: CGRect) {
    super.init(frame: frame)

    self.autoSetDimension(.Height, toSize: 44)
    titleLabel.backgroundColor = UIColor.clearColor()
    titleLabel.translatesAutoresizingMaskIntoConstraints = false
    titleLabel.numberOfLines = 0
    self.addSubview(titleLabel)

    titleLabel.text = "Some text"
    titleLabel.sizeToFit()

    titleLabel.autoPinEdgeToSuperviewEdge(.Leading, withInset: 20)
    titleLabel.autoPinEdgeToSuperviewEdge(.Trailing, withInset: 20)
    titleLabel.autoAlignAxisToSuperviewAxis(.Horizontal)
}

实际上,标签的文本可能会在运行时更改,但无论如何,当我运行应用程序时,我看不到标签在其父视图中垂直居中......有人可以帮我解决这个问题吗?

提前致谢

4

1 回答 1

0

看看这个,如果它可以帮助你,

let label = UILabel()
    label.translatesAutoresizingMaskIntoConstraints = false

label.text = "Some dummy text"
self.view.addSubview(label)

let centreH = NSLayoutConstraint(item: label, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 1)

let centreV = NSLayoutConstraint(item: label, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 1)

self.view.addConstraint(centreH)
self.view.addConstraint(centreV)
于 2016-03-11T13:07:16.220 回答