试图将UIButton变成圆圈

问题描述 投票:0回答:3

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

  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
}()

但是,当我运行代码时,该按钮被毁坏了,看起来像下面的……圆形和橄榄球状。enter image description here

有什么理由使按钮看起来像它而不是圆形吗?

ios swift xcode uiview uibutton
3个回答
1
投票

您是否在使用自动布局感到困惑。

您已经将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
}()

enter image description here


1
投票

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

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


1
投票

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

anyButton.backgroundColor = .clear

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

anyButton.layer.borderWidth = 1

anyButton.layer.borderColor = UIColor.black.cgColor
© www.soinside.com 2019 - 2024. All rights reserved.