user8480321
user8480321

Reputation: 15

Set X and Y values of UILabel using NSLayout

I am adding a UI Label and I am trying out programmatic UI code. I set up my label using this code:

let titleLabel: UILabel = {
    let lb = UILabel()
    lb.translatesAutoresizingMaskIntoConstraints = false
    lb.textAlignment = .center
    lb.numberOfLines = 1
    lb.textColor = UIColor.black
    lb.font=UIFont.systemFont(ofSize: 22)
    lb.backgroundColor = UIColor.white
    return lb

and then added constraints using this code:

func setupTitleLabel() {


    titleLabel.translatesAutoresizingMaskIntoConstraints = false
    titleLabel.heightAnchor.constraint(equalToConstant: 100).isActive = true
    titleLabel.widthAnchor.constraint(equalToConstant: 200).isActive = true
    titleLabel.centerXAnchor.constraint(equalTo: titleLabel.superview!.centerXAnchor).isActive = true
    titleLabel.centerYAnchor.constraint(equalTo: titleLabel.superview!.centerYAnchor).isActive = true
}

I call this function later on. However, I am not sure how to change to X and Y values. Currently, it is set to the middle of the page for both X and Y, but how would I move it up to the top.

Upvotes: 1

Views: 204

Answers (2)

user8496305
user8496305

Reputation:

What I understand the case is that the label is in the centerX and centerY, and you want it to be at the top of the superView later.If so,I think you can use var centerYAnchor: NSLayoutConstraint?

centerYAnchor = titleLabel.centerYAnchor.constraint(equalTo: titleLabel.superview!.centerYAnchor)
centerYAnchor.isActive = true

And when you want to change the label at the top later,you can set centerYAnchor.isActive = false and set the label's topAnchor.

 titleLabel.topAnchor.constraint(equalTo: titleLabel.superview!.topAnchor).isActive = true

Upvotes: 0

Reinier Melian
Reinier Melian

Reputation: 20804

As I said in my comment, you are using titleLabel.superview!.centerYAnchor wrongly if you need pin your label to top of your label superview you need use titleLabel.superview!.topAnchor instead

replace this

titleLabel.centerYAnchor.constraint(equalTo: titleLabel.superview!.centerYAnchor).isActive = true

by this

titleLabel.centerYAnchor.constraint(equalTo: titleLabel.superview!.topAnchor).isActive = true

Upvotes: 1

Related Questions