Vale
Vale

Reputation: 17

Is it possible to add constraint between two UILabels?

Yeah basically i want to create a constraint between the bottom border of one UILabel (label1) and top border of another UILabel (label2). I currently have the top of my label 1 connected to the safearea and constant height set up to 100.

    let label1 = UILabel.init()
    label1.text = "123"
    view.addSubview(label1)
    label1.translatesAutoresizingMaskIntoConstraints = false
    label1.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true
    label1.heightAnchor.constraint(equalToConstant: 100).isActive = true


    let label2 = UILabel.init()
    label2.text = "456"
    view.addSubview(label2)
    label2.translatesAutoresizingMaskIntoConstraints = false
    label2.topAnchor.constraint(???)

Upvotes: 0

Views: 116

Answers (2)

Najeeb ur Rehman
Najeeb ur Rehman

Reputation: 413

Simply use vertical stackview .

let label1 = UILabel()
label1.text = "123"

let label2 = UILabel()
label2.text = "456"


let stackView = UIStackView(arrangedSubviews: [label1, label2])
stackView.axis = .vertical
stackView.distribution = .equalSpacing
stackView.alignment = .center
stackView.spacing = 10
stackView.translatesAutoresizingMaskIntoConstraints = false 

 NSLayoutConstraint.activate([ 
       stackView.topAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.topAnchor,constant:20.0),
      stackView.centerXAnchor.constraint(equalTo:self.view.centerXAnchor)
])  

Upvotes: 0

Shehata Gamal
Shehata Gamal

Reputation: 100523

You need

let label1 = UILabel()
label1.text = "123"
view.addSubview(label1)
label1.translatesAutoresizingMaskIntoConstraints = false

let label2 = UILabel()
label2.text = "456"
view.addSubview(label2)
label2.translatesAutoresizingMaskIntoConstraints = false 

NSLayoutConstraint.activate([ 
   label1.topAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.topAnchor,constant:20.0),
   label1.centerXAnchor.constraint(equalTo:self.view.centerXAnchor),
   label2.topAnchor.constraint(equalTo: self.label1.bottomAnchor,constant:20.0),
   label2.centerXAnchor.constraint(equalTo:self.view.centerXAnchor)
])   

You can also use a vertical UIStackView

Upvotes: 1

Related Questions