如何在Swift中将多个按钮水平居中?

时间:2019-02-08 05:32:47

标签: swift

我正在以编程方式创建多个按钮。例如,如果我要创建两个按钮,且两个按钮之间的间距已定义,则要将这两个按钮在视图控制器中水平居中。我该如何迅速完成此任务?

2 个答案:

答案 0 :(得分:2)

UIStackView是您要寻找的。

示例

首先声明btn1btn2,然后将其放入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)

您可以将UIStackViewhorizontal轴属性一起使用,在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)
        ])
    }
}

这是视图:

botton_center_buttons

在操场上玩这个代码,然后根据您的要求进行更改。