如何将 UIButton 转换为圆形?
Posted
技术标签:
【中文标题】如何将 UIButton 转换为圆形?【英文标题】:How can I transform UIButton to circle? 【发布时间】:2020-08-27 08:32:08 【问题描述】:我正在尝试将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
两者都没有帮助。尝试将形状更改为圆形时添加 UIButton 的图像(黄色按钮)
【问题讨论】:
你能告诉我们currentSignInButtonState
cornerRadius
是动画属性,不需要转换。
@MohmmadS 添加到代码中,现在
@vpoltave 我使用变换来降低宽度以匹配高度。获得 1:1 的纵横比
你能附上你的结果图片吗?
【参考方案1】:
在您更新后,我发现了您的宽度,问题在于转换,因为它使 .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
【讨论】:
我不明白。解决方案和我发布的问题有什么区别? 你的标志也弄错了我不知道你在哪里调用了我从按钮上的 didTap 假设的这个函数 @SidharthJDev 试试看,它对我也很好,即使您在点击后也从 didLoad 调用它也可以正常工作。您的错误是将其设置为在您的情况下单击并在您的情况正常时正常 @SidharthJDev 检查视频,您的代码在标志设置中有一个错误,表明与您的代码有什么不同 尝试从确实加载然后点击时调用它以上是关于如何将 UIButton 转换为圆形?的主要内容,如果未能解决你的问题,请参考以下文章