试图使 UIButton 成为一个圆圈

Trying to make a UIButton a circle

我目前正在尝试将按钮制作成圆形,这是我的代码:

  var raffleButton:UIButton = {
    var button = UIButton()
    button.translatesAutoresizingMaskIntoConstraints = false
    button.titleLabel?.font = UIFont(name: "AvenirNext-Bold", size: 19)
    button.setTitle("Tap To Enter Raffle!", for: .normal)
    button.setTitleColor(UIColor.red, for: .normal)
    button.backgroundColor = .white
    button.layer.masksToBounds = true

    button.frame = CGRect(x: 1600, y: 160, width: 160, height: 160)
    button.layer.cornerRadius = button.frame.width/2

    return button
}()

然而,当我 运行 代码时,按钮被毁容并且看起来像下面...圆形和足球一样。

为什么按钮看起来像它而不是一个圆圈?

您对是否使用自动版式有些困惑。

您已将 translatesAutoresizingMaskIntoConstraints 设置为 false,但随后您试图操纵框架。

如果您添加约束来设置宽度和高度,您会得到更接近您所追求的结果,但您仍然需要调整标签或字体以使其适合:

var raffleButton:UIButton = {
    var button = UIButton()
    button.translatesAutoresizingMaskIntoConstraints = false
    button.titleLabel?.font = UIFont(name: "AvenirNext-Bold", size: 19)
    button.setTitle("Tap To Enter Raffle!!", for: .normal)
    button.setTitleColor(UIColor.red, for: .normal)
    button.backgroundColor = .white
    button.layer.masksToBounds = true

    button.heightAnchor.constraint(equalToConstant: 160).isActive = true
    button.widthAnchor.constraint(equalToConstant: 160).isActive = true
    button.layer.cornerRadius = 80

    return button
}()

由于您设置了 button.translatesAutoresizingMaskIntoConstraints = false,此代码将不起作用 button.frame = CGRect(x: 1600, y: 160, width: 160, height: 160)。按钮的大小将在布局过程中更改(不再是 (160, 160))。所以不是圆

您可以更改 button.translatesAutoresizingMaskIntoConstraints = false 或尝试在 viewDidLayoutSubviews 方法中设置按钮的 cornerRadius

您的按钮高度与按钮宽度相同,然后设置此代码..

anyButton.backgroundColor = .clear

anyButton.layer.cornerRadius = anyButton.frame.height / 2

anyButton.layer.borderWidth = 1

anyButton.layer.borderColor = UIColor.black.cgColor