Evgeniy Kleban
Evgeniy Kleban

Reputation: 6965

Add uibutton with Auto Layout programmatically

I want to add UIButton like this:

 let switchTheme: UIButton = {
    let button = UIButton.init()
    button.backgroundColor = .red
    button.setTitleColor(.blue, for: .normal)
    button.setTitle(Settings.isLightTheme() ? Strings.Various.switchToDark.value : Strings.Various.switchToLight.value, for: .normal)
    button.translatesAutoresizingMaskIntoConstraints = false
    return button
}()

And then set constraints like:

switchTheme.bottomAnchor.constraint(equalTo: view.bottomAnchor)
switchTheme.leftAnchor.constraint(equalTo: view.leftAnchor)
switchTheme.rightAnchor.constraint(equalTo: view.rightAnchor)
switchTheme.heightAnchor.constraint(equalToConstant: 40.0)

But it shown not on bottom as it suppose to but on top and without constraints applied.

enter image description here

Upvotes: 1

Views: 804

Answers (3)

user9106403
user9106403

Reputation:

You will need to set constraints activate state = true. You can do it simply,

NSLayoutConstraint.activate([
    //Move your existing code HERE with comma separated
])

In case of any problem, you can check this following function:

func setConstraints() {
    NSLayoutConstraint.activate([
        switchTheme.bottomAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.bottomAnchor), // bottomAnchor to set bottom target.
        switchTheme.leftAnchor.constraint(equalTo: self.view.leftAnchor), // leftAnchor to set X left
        switchTheme.rightAnchor.constraint(equalTo: self.view.rightAnchor), // rightAnchor to set X right
        switchTheme.heightAnchor.constraint(equalToConstant: 40.0) //heightAnchor to set appropriate height.
    ])
}

Upvotes: 2

Mathias
Mathias

Reputation: 566

Your constrains must be activated :

switchTheme.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true

Upvotes: 2

Tung Vu Duc
Tung Vu Duc

Reputation: 1662

You need to active those constraints just simple like this :

 switchTheme.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
 switchTheme.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
 switchTheme.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
 switchTheme.heightAnchor.constraint(equalToConstant: 40.0).isActive = true

Upvotes: 2

Related Questions