如何为一条线设置动画,使其变大?

How to animate a line so that it gets bigger?

我在 Xcode 中创建了一个空白项目并添加了一个按钮。我将它居中并将其高度和宽度设置为 60。这是我的代码:

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)
        
    }
    
}

当我单击按钮时,我希望按钮的宽度从 5 像素变为 60 像素。我也想为此设置动画,但我遇到了麻烦。到目前为止,当我点击按钮时没有任何反应。有人能帮我吗?

不要创建新视图。只需更改您已有的框架即可:

UIView.animate(withDuration: 4.0, animations: {
    
    self.lineView.frame = CGRect(x: 0, y: 60, width: self.button.frame.width, height: 1)

}, completion: nil)