Reputation: 987
I am trying to animate a UIButton
to circular shape, when user clicks on it. But I am getting the top part of the UIView
as flat when I try to do that. Pasting my code below.
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
}
}
}
I have also tried adding
self.clipsToBounds = true
self.layer.masksToBounds = true
Neither helped. Adding the image of the UIButton when tried to change shape to circle(button in yellow)
Upvotes: 0
Views: 124
Reputation: 5088
After your update, I found out about your width, the issue is in transform as it makes the .cornerRadius
misbehave, trying another approach would solve it
So we need to create another width constraint with a constant value
and create IBOutlets
in code for both, and change the priority of each when clicked and changing the values while changing corner radius, check below
@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
}
}
}
Upvotes: 1