UIKit 是 iOS 开发的核心框架,其动画功能能为应用增添流畅的交互体验。以下是 UIKit 动画的基础知识与实践技巧:
一、基础动画实现
UIView 动画
使用UIView.animate(withDuration:animations:)
方法实现简单过渡:UIView.animate(withDuration: 0.5) { self.view.alpha = 0.5 }
核心动画(Core Animation)
通过CABasicAnimation
实现更复杂的图层动画:let animation = CABasicAnimation(keyPath: "transform.rotation") animation.fromValue = 0 animation.toValue = CGFloat.pi * 2 layer.add(animation, forKey: "rotation")
CoreAnimation_关键帧
二、高级动画技巧
关键帧动画
使用CAKeyframeAnimation
定义多点控制动画路径:let keyframe = CAKeyframeAnimation(keyPath: "position") keyframe.values = [CGPoint(x: 0, y: 0), CGPoint(x: 100, y: 100)] keyframe.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
📎 了解更多动画类型
动画延迟与重复
设置beginTime
控制延迟,repeatCount
实现循环效果:animation.beginTime = CACurrentMediaTime() + 1.0 animation.repeatCount = .infinity
UIView_动画示例
三、动画性能优化
- 使用
layoutIfNeeded()
在动画中确保布局更新:UIView.animate(withDuration: 0.3) { self.view.layoutIfNeeded() }
- 避免频繁重绘
通过opaque
属性优化视图透明度:view.opaque = true
- 动画与手势冲突处理
优先级设置:animation.isRemovedOnCompletion = false
四、实用工具与资源
- 📌 动画调试工具推荐
- 🧠 动画原理图解:UIKit_动画原理
- 📚 官方文档参考:Apple UIKit Animation Guide
五、常见问题
- ✅ 动画卡顿?检查主线程阻塞
- ❌ 动画未生效?确认
isUserInteractionEnabled
为 true - ⏱️ 动画同步?使用
UIViewAnimationOptions.curveLinear