【问题标题】:Trying to make a UIButton a circle试图使 UIButton 成为一个圆圈
【发布时间】:2020-06-06 14:56:35
【问题描述】:

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

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

但是,当我运行代码时,按钮已损坏,看起来像以下...圆形和足球。

按钮看起来像它而不是一个圆圈有什么原因吗?

【问题讨论】:

    标签: ios swift xcode uiview uibutton


    【解决方案1】:

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

    anyButton.backgroundColor = .clear
    
    anyButton.layer.cornerRadius = anyButton.frame.height / 2
    
    anyButton.layer.borderWidth = 1
    
    anyButton.layer.borderColor = UIColor.black.cgColor
    

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        【解决方案3】:

        您对是否使用自动布局有些困惑。

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

        【讨论】:

          猜你喜欢
          • 2017-12-06
          • 2016-10-12
          • 2015-04-15
          • 1970-01-01
          • 2015-05-16
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多