1

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

pacification
  • 5,838
  • 4
  • 29
  • 51
Evgeniy Kleban
  • 6,794
  • 13
  • 54
  • 107
  • Check this : https://stackoverflow.com/questions/26180822/how-to-add-constraints-programmatically-using-swift/45328791 – Amit Mar 11 '19 at 05:48

3 Answers3

2

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
Tung Vu Duc
  • 1,552
  • 1
  • 13
  • 22
2

Your constrains must be activated :

switchTheme.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
Mathias
  • 556
  • 9
  • 21
2

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.
    ])
}
Mayur Karmur
  • 2,119
  • 14
  • 35