我正在尝试将cornerRadiusUIButton设置为看起来像圆形,但我无法做到。

这是我尝试过的代码。

func addColorButton() {
    let colorButton : UIButton = {
        let cb = UIButton()
        cb.translatesAutoresizingMaskIntoConstraints = false
        cb.backgroundColor = .black

        return cb
    }()

    view.addSubview(colorButton)
    colorButton.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
    colorButton.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -10).isActive = true
    colorButton.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.5).isActive = true
    colorButton.heightAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.5).isActive = true
    colorButton.layer.cornerRadius = 0.5 * colorButton.bounds.size.width
    print(colorButton.bounds.width)
    colorButton.clipsToBounds = true

}
 override func viewDidLoad() {
    super.viewDidLoad()

   addColorButton()
}

最佳答案

在自动布局完成之前,不会设置按钮边界/框架。
您可以更新,

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()

    // Update corner radius here
    colorButton.layer.cornerRadius = 0.5 * colorButton.bounds.size.width
}

10-08 01:35