代码之家  ›  专栏  ›  技术社区  ›  Evgeniy Kleban

以编程方式添加带有自动布局的uibutton

  •  1
  • Evgeniy Kleban  · 技术社区  · 7 年前

    我想添加这样的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

    2 回复  |  直到 7 年前
        1
  •  2
  •   Mayur Karmur    7 年前

    您将需要设置约束 activate state = true .你可以做得很简单,

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

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

    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.
        ])
    }
    
        2
  •  2
  •   Tung Vu Duc    7 年前

    您需要激活这些约束,如下所示:

     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
    
        3
  •  2
  •   Mathias    7 年前

    必须激活约束:

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