I created just a blank project in Xcode and added a button. I centered it and set its height and width to 60. Heres my code:
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var button: UIButton!
var lineView = UIView(frame: CGRect(x: 0, y: 60, width: 5, height: 1))
override func viewDidLoad() {
super.viewDidLoad()
lineView.backgroundColor = UIColor.black
button.addSubview(lineView)
}
@IBAction func sampleButton(_ sender: Any) {
UIView.animate(withDuration: 4.0, animations: {
self.lineView = UIView(frame: CGRect(x: 0, y: 60, width: self.button.frame.width, height: 1))
self.button.addSubview(self.lineView)
}, completion: nil)
}
}
When I click the button I want the width to go from being 5 pixels to the width of the button which is 60. I also want to animate this but I am having trouble. So far when I click the button nothing happens. Would anyone be able to help me out?
Don't create a new view. Just change the frame of the one you already have:
UIView.animate(withDuration: 4.0, animations: {
self.lineView.frame = CGRect(x: 0, y: 60, width: self.button.frame.width, height: 1)
}, completion: nil)