我正在以编程方式创建多个按钮。例如,如果我要创建两个按钮,且两个按钮之间的间距已定义,则要将这两个按钮在视图控制器中水平居中。我该如何迅速完成此任务?
答案 0 :(得分:2)
UIStackView
是您要寻找的。 p>
示例
首先声明btn1
,btn2
,然后将其放入UIStackView
。
lazy var horizontalStackView: UIStackView = {
let sv = UIStackView(arrangedSubviews: [
btn1,
btn2
])
sv.axis = .horizontal
sv.spacing = 8
return sv
}()
override func viewDidLoad() {
view.addSubview(horizontalStackView)
// Then setup its constraint of horizontalStackView
horizontalStackView.translatesAutoresizingMaskIntoConstraints = false
horizontalStackView.topAnchor...
}
最后,您只需要像普通的horizontalStackView
那样将UIView
锚定到所需位置即可。
答案 1 :(得分:0)
您可以将UIStackView
与horizontal
轴属性一起使用,在UIStackView
内添加按钮,并在stackView上添加约束以使其在视图中居中。
这是一个简单的示例,将两个按钮平均居中在屏幕底部,比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)
])
}
}
这是视图:
在操场上玩这个代码,然后根据您的要求进行更改。