以编程方式使用自动布局添加uibutton

时间:2019-03-11 01:11:38

标签: swift autolayout

我想这样添加UIButton:

 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
}()

然后设置约束,例如:

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

但是它并没有像预期的那样显示在底部,而是显示在顶部,并且没有施加约束。

enter image description here

3 个答案:

答案 0 :(得分:2)

您将需要设置约束LOGIN_REDIRECT_URL = '/' LOGOUT_REDIRECT_URL = '/' //change as you wish 。您可以轻松做到,

activate state = true

如果有任何问题,您可以检查以下功能:

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

答案 1 :(得分:1)

您需要像这样简单地激活这些约束:

 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

答案 2 :(得分:1)

您的约束必须被激活:

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