import UIKit
class ViewController: UIViewController,UICollisionBehaviorDelegate {
//UIKIt重力引擎
var animator:UIDynamicAnimator?
//重力行为
var gravity :UIGravityBehavior?
//碰撞行为
var collision:UICollisionBehavior?
var square: UIView?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
square = UIView(frame: CGRect(x: 160, y: 10, width: 90, height: 90))
square?.backgroundColor = UIColor.gray
self.view.addSubview(square!)
let barrier = UIView(frame: CGRect(x: 0, y: 380, width: 180, height: 20))
barrier.backgroundColor = UIColor.red
self.view.addSubview(barrier)
//运动管理
animator = UIDynamicAnimator(referenceView: self.view)
//创建运动行为
gravity = UIGravityBehavior(items: [square!])
//角度
gravity?.angle = 1.6
//速度
gravity?.magnitude = 0.1
//
//collision = UICollisionBehavior(items: [square,barrier])
collision = UICollisionBehavior(items: [square!])
collision?.addBoundary(withIdentifier: "barrier" as NSCopying, for: UIBezierPath(rect: barrier.frame))
collision?.translatesReferenceBoundsIntoBoundary = true
animator?.addBehavior(gravity!)
animator?.addBehavior(collision!)
collision?.collisionDelegate = self
collision?.action = {
print("transfrom:\(String(describing:self.square?.transform)) center:\(String(describing:self.square?.center))")
}
let itemBehavior = UIDynamicItemBehavior(items: [square!])
itemBehavior.elasticity = 0.6
animator?.addBehavior(itemBehavior)
//运动轨迹添加
var updateCount = 0
collision?.action = {
if (updateCount % 3 == 0) {
let outline = UIView(frame: (self.square?.bounds)!)
outline.transform = (self.square?.transform)!
outline.center = (self.square?.center)!
outline.alpha = 0.5
outline.backgroundColor = UIColor.clear
outline.layer.borderColor = self.square?.layer.presentation()?.borderColor
outline.layer.borderWidth = 1.0
self.view.addSubview(outline)
}
updateCount += 1
}
}
func collisionBehavior(_ behavior:UICollisionBehavior, beganContactFor item:UIDynamicItem,withBoundaryIdentifier indentifier:NSCopying?,at p:CGPoint) {
let view = item as? UIView
view?.backgroundColor = UIColor.yellow
UIView.animate(withDuration: 0.3, animations: {
view?.backgroundColor = UIColor.gray
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
网友评论