Search code examples
iosswiftxcodenslayoutconstraint

NSLayoutConstraints on objects swift 3.0


Currently I am using this line of code to set the origin on a UILabel at the top left corner...

addConstraint(NSLayoutConstraint(item: messageLabel, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1, constant: 0))

However I want the origin to be 0 pixels from left edge H and half of height if that makes sense.

Any suggestions? I've tried changing the multiplier to no avail.

What I am trying to do is move the origin so that (0,0) instead of being the top left corner, is the furthermost left of the label and half of the label height so that I can center the label properly.


Solution

  • Just to clarify, you need the label left aligned and centered top to bottom?

    Have you looked at NSLayoutAnchor?

    messageLabel = UILabel(/* Initialized somehow */)
    messageLabel.translatesAutoresizingMaskIntoConstraints = false
    
    view.addSubview(messageLabel)
    view.centerYAnchor.constraint(equalTo: messageLabel.centerYAnchor).isActive = true
    view.leadingAnchor.constraint(equalTo: messageLabel.leadingAnchor).isActive = true