import UIKit
import QuartzCore
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let targetView = UIView(frame: CGRect(x: 100, y: 100, width: 200, height: 200))
targetView.backgroundColor = .red
view.addSubview(targetView)
let fadeInAnimation = CABasicAnimation(keyPath: "opacity")
fadeInAnimation.fromValue = 0
fadeInAnimation.toValue = 1
fadeInAnimation.duration = 2 // 动画持续时间为2秒
fadeInAnimation.delegate = self
targetView.layer.add(fadeInAnimation, forKey: "fadeInAnimation")
}
}
extension ViewController: CAAnimationDelegate {
func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
if flag {
print("动画完成")
// 这里可以添加动画完成后的回调处理逻辑
}
}
}