我正在以编程方式创建多个按钮。例如,如果我正在创建两个按钮之间定义了间距的按钮,我想在 View Controller 中将这两个按钮水平居中。我怎样才能用 swift 做到这一点?
最佳答案
您可以将 UIStackView
与 horizontal
轴属性一起使用,在 UIStackView
中添加按钮,并在 stackView 上添加约束以在 View 中居中。
这是一个简单的例子,将两个按钮在屏幕底部平均居中,比 safeAreaLayout 引用线高 8 点。
class ViewController: UIViewController {
lazy var button1: UIButton = {
let button = UIButton()
button.translatesAutoresizingMaskIntoConstraints = false
button.backgroundColor = .red
button.setTitle("Button1", for: .normal)
return button
}()
lazy var button2: UIButton = {
let button = UIButton()
button.translatesAutoresizingMaskIntoConstraints = false
button.backgroundColor = .blue
button.setTitle("Button2", for: .normal)
return button
}()
lazy var horizontalStackView: UIStackView = {
let stackView = UIStackView(arrangedSubviews: [button1, button2])
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.axis = .horizontal
stackView.distribution = .fillEqually
stackView.spacing = 8
return stackView
}()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(horizontalStackView)
NSLayoutConstraint.activate([
horizontalStackView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -8),
horizontalStackView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 8),
horizontalStackView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -8),
horizontalStackView.centerXAnchor.constraint(equalTo: view.centerXAnchor),
horizontalStackView.heightAnchor.constraint(equalToConstant: 50)
])
}
}
这是 View :
在 playground 中尝试使用此代码并根据您的要求进行更改。
关于swift - 如何在 Swift 中水平居中多个按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54586519/