今天我们要学习UIDynamicAnimator 仿真物理学 。
- 创建运动管理
- 创建运动行为(如gravity、collision),运动行为添加运动物体:即需要指定具体物体(具体物体,具体行为)
- 当需要使用运动物体的某种行为,就用运动管理添加运动行为
- 一般还要注意remove
import UIKit
class ViewController: UIViewController {
var animator: UIDynamicAnimator?
override func viewDidLoad() {
super.viewDidLoad()
//下落的方块
let square = UIView(frame: CGRect(x: 120, y: 50, width: 80, height: 80))
square.backgroundColor = UIColor.cyan
self.view.addSubview(square)
//边界:栏杆
let barrier = UIView(frame: CGRect(x: 0, y: 350, width: 140, height: 25))
barrier.backgroundColor = UIColor.red
self.view.addSubview(barrier)
//创建运动管理
animator = UIDynamicAnimator(referenceView: self.view)
//创建运动行为:gravity、collision——>需要指定具体物体(具体物体,具体行为)
let gravity = UIGravityBehavior(items: [square])
let collision = UICollisionBehavior(items: [square])
let elastic = UIDynamicItemBehavior(items: [square])
//添加边界(不可见)——而不是barrier(它只是给人以视觉上的边界)
let right = CGPoint(x: barrier.frame.origin.x + barrier.frame.size.width, y: barrier.frame.origin.y) //而left是barrier.frame.orign,这两个都是CGPoint,就只有x和y属性
//将参考视图(父视图)的边界作为碰撞边界
collision.translatesReferenceBoundsIntoBoundary = true
//将barrier作为碰撞边界
collision.addBoundary(withIdentifier: "aa" as NSCopying, from: barrier.frame.origin, to: right)
//实现弹性效果
elastic.elasticity = 1.12
animator?.addBehavior(gravity)
animator?.addBehavior(collision)
animator?.addBehavior(elastic)
}
}