如何解决如何将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的图像(黄色按钮)
解决方法
更新后,我发现了宽度,问题出在转换上,因为它会使.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
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。