以编程方式添加带有自动布局的uibutton
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了以编程方式添加带有自动布局的uibutton相关的知识,希望对你有一定的参考价值。
我想像这样添加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)
但它不是在底部显示,而是在顶部并且没有应用约束。
答案
您需要设置约束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.
])
}
另一答案
你需要像这样简单地激活这些约束:
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
另一答案
您的约束必须激活:
switchTheme.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
以上是关于以编程方式添加带有自动布局的uibutton的主要内容,如果未能解决你的问题,请参考以下文章
如何在标准 UITableViewCell 中以编程方式自动布局右侧的自定义 UIButton。