Kobe Kobe - 1 month ago 14
iOS Question

How to animate UIButton frame from left to right and reverse

My current method is to add a view to the button as subview:

let button = UIButton(frame: CGRect(x: 0, y: 0, width: 0, height: 60))
button.setTitle("Add", for: .normal)
buttonView = UIView(frame: CGRect(x: 0, y: 0, width: 0, height: 60))
buttonView.backgroundColor = .black
button.addSubview(buttonView)


And then animate the width of the view:

UIView.animate(withDuration: 0.3, delay: 0.0, options: .curveEaseIn, animations: {
self.buttonView.frame = CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 60)
}, completion: nil)


What I don't like about this is that the button title remains static. I want it to be part of the animation.

I also try to animate the frame of the button instead, but it doesn't seem to work. Nothing happens.

My button is added to the
UITextField
inputAccessoryView
so I am not sure if this is the problem.

Any suggestions how can I animate the button correctly ?

Answer

You don't need an additional subview for UIButton in order to animate it's frame.

Try to add layoutIfNeeded() before animation and inside animation closure:

let button = UIButton(frame: CGRect(x: 0, y: 0, width: 60, height: 60))
button.setTitle("Add", for: .normal)
button.setTitleColor(UIColor.green, for: .normal)
button.backgroundColor = UIColor.black

view.addSubview(button)
button.layoutIfNeeded()

UIView.animate(withDuration: 3, delay: 0.0, options: .curveEaseIn, animations: {
    button.frame = CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 60)
    button.layoutIfNeeded()
    }, completion: nil)

Hope this helps.

Comments