Vertically aligning a label with PureLayout

579 Views Asked by At

I have a simple UIView subclass that contains a label. This subclass has the following init method:

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)
}

Actually, the text of the label could change at runtime, but anyway, I don't see the label vertically centered within its parent view when I run the app... could somebody help me with this?

Thanks in advance

1

There are 1 best solutions below

0
On

See this, if it could help you,

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)