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

标签 swift

我正在以编程方式创建多个按钮。例如,如果我正在创建两个按钮之间定义了间距的按钮,我想在 View Controller 中将这两个按钮水平居中。我怎样才能用 swift 做到这一点?

最佳答案

您可以将 UIStackViewhorizo​​ntal 轴属性一起使用,在 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 :

botton_center_buttons

在 playground 中尝试使用此代码并根据您的要求进行更改。

关于swift - 如何在 Swift 中水平居中多个按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54586519/

相关文章:

ios - 类型 NSArray 不能被隐式向下转换

swift - UIScrollView 点击按钮不起作用

ios - '数组 <(对象)>' is not convertible to ' bool 值'

swift - 在 swift 中,什么时候在声明类时显式使用访问修饰符 "internal"会产生任何影响?

ios - 滑动动画和功能

multithreading - Swift 中的线程间通信?

ios - hanekeswift 从所有 FormatName 中删除图像

swift cgsize 错误参数标签 '(_:, _:)' 不匹配任何可用的重载

ios - Swift 中没有调用 UIProgressView 的 observeValueForKeyPath

swift - 在另一个类中实例化的弱引用在 Swift 中返回 nil