如何将UIButton转换为圆形?

问题描述

用户单击UIButton时,我试图将其UIView设置为圆形。但是,当我尝试这样做时,private enum SignInButtonState { case clicked case normal } private var currentSignInButtonState: SignInButtonState = .normal private func updateSignInButton(to state: SignInButtonState) { switch state { case .clicked: signinButton.setTitle("",for: .normal) self.currentSignInButtonState = .clicked UIView.animate(withDuration: 0.5) { self.signinButton.transform = CGAffineTransform(scaleX: self.signinButton.frame.height/self.signinButton.frame.width,y: 1) self.signinButton.layer.cornerRadius = self.signinButton.frame.height/2 } case .normal: signinButton.setTitle("Sign In",for: .normal) self.currentSignInButtonState = .normal UIView.animate(withDuration: 0.5) { self.signinButton.transform = CGAffineTransform(scaleX: 1,y: 1) self.signinButton.layer.cornerRadius = 5.0 } } } 的顶部变得平坦。在下面粘贴我的代码

        self.clipsToBounds = true
        self.layer.masksToBounds = true

我也尝试添加

{{1}}

都没有帮助。尝试将形状更改为圆形时添加UIButton的图像(黄色按钮)

Gif of what is happening

Current output of UIButton being a circle

解决方法

更新后,我发现了宽度,问题出在转换上,因为它会使.cornerRadius行为异常,请尝试另一种方法可以解决

  • 我可以看到您的宽度==以查看宽度

所以我们需要创建另一个具有恒定值的宽度约束 并在两者中的代码中创建IBOutlets,并在单击时更改每个对象的优先级,并在更改拐角半径时更改其值,请检查以下内容

@IBOutlet weak var secondWidthConstant: NSLayoutConstraint! // this is the constant one
@IBOutlet weak var widthOfBtn: NSLayoutConstraint! // this is the one that has == to super.view

  private func updateSignInButton(to state: SignInButtonState) {
    switch state {
    case .clicked:
        signinButton.setTitle("",for: .normal)
        self.currentSignInButtonState = .normal
        widthOfBtn.priority = UILayoutPriority(rawValue: 750) // this one is the constraint that is == to the width of the view
        secondWidthConstant.priority = UILayoutPriority(rawValue: 1000) // this is the constant value constraint
        secondWidthConstant.constant = self.signinButton.frame.height // change the constant after the priorty is set to higher than the == one
        UIView.animate(withDuration: 0.5,animations: {
            self.signinButton.layoutIfNeeded()
            self.signinButton.layer.cornerRadius = (self.signinButton.frame.height / 2)
        }) { (_) in
        }
    case .normal:
        widthOfBtn.priority = UILayoutPriority(rawValue: 1000) //switch back priorty
        secondWidthConstant.priority = UILayoutPriority(rawValue: 750) //switch back priorty
        signinButton.setTitle("Sign In",for: .normal)
        self.currentSignInButtonState = .clicked
        UIView.animate(withDuration: 0.5) {
            self.signinButton.layoutIfNeeded()
            self.signinButton.layer.cornerRadius = 5.0
        }
    }
}

enter image description here