//
// ViewController.swift
// UIDynamic的使用
//
// Created by admin on 16/2/29.
// Copyright © 2016年 jin. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var viewA: UIView!
override func viewDidLoad() {
super.viewDidLoad()
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
let touche = (touches as! NSSet).anyObject()
self.snap((touche?.locationInView(self.view))!)
}
// 创建仿真器并指定仿真范围
lazy var animator:UIDynamicAnimator = UIDynamicAnimator(referenceView: self.view)
// 捕捉行为
func snap(point:CGPoint)
{
// MARK: 创建仿真器
self.animator.removeAllBehaviors()
// MARK: 创建行为
let snap = UISnapBehavior(item: self.viewA, snapToPoint: point)
// 设置阻力
snap.damping = 1000
// 把行为加入到仿真器
self.animator.addBehavior(snap)
}
// 重力行为仿真测试
func gravityAttr()
{
// MARK: 创建仿真器
// MARK: 创建行为
let collision = UICollisionBehavior(items: [self.viewA])
collision.translatesReferenceBoundsIntoBoundary = true
let gravity = UIGravityBehavior(items: [self.viewA])
// MARK: 属性设置
// 重力角度,默认是 90
gravity.angle = CGFloat(M_PI * 0.1)
// 重力的大小,太大的话view会直接消失,应该是被重力压扁了吧。。。。
gravity.magnitude = 1
// 向量:具有大小和方向
gravity.gravityDirection = CGVectorMake(3, 1)
// MARK: 添加行为到仿真器
self.animator.addBehavior(collision)
self.animator.addBehavior(gravity)
}
// 碰撞行为仿真属性测试
func collisionAttr()
{
// MARK: 创建仿真器并指定范围
// MARK: 创建行为
// 碰撞行为
let collision = UICollisionBehavior(items: [self.viewA])
// 把仿真器的bounds作为碰撞的边界
collision.translatesReferenceBoundsIntoBoundary = true
// 重力行为
let gravity = UIGravityBehavior(items: [self.viewA])
// MARK: 属性测试
// 添加边界-线段
let start = CGPointMake(0, self.view.bounds.size.height * 0.5 + self.viewA.bounds.size.height * 0.5)
let end = CGPointMake(self.view.bounds.size.width, self.view.bounds.size.height * 0.5 + self.viewA.bounds.size.height * 0.5)
collision.addBoundaryWithIdentifier("line", fromPoint: start, toPoint: end)
// 添加一条path,view掉下来的时候会像在圆里面滚动
let bezier = UIBezierPath(ovalInRect: CGRectMake(0, 0 - self.view.bounds.width * 0.5, self.view.bounds.width, self.view.bounds.width))
collision.addBoundaryWithIdentifier("bezier", forPath: bezier)
// MARK: 把仿真行为添加到仿真器中
self.animator.addBehavior(collision)
self.animator.addBehavior(gravity)
}
// 重力行为和碰撞行为,view会调到屏幕的下面停住,类似物体落地
func gravityAndCollision()
{
// 创建仿真器并指定范围
// 创建重力行为
let gravityBehavior = UIGravityBehavior(items: [self.viewA])
// 创建碰撞行为
let collisionBehavior = UICollisionBehavior(items: [self.viewA])
// 指定碰撞行为边界
collisionBehavior.translatesReferenceBoundsIntoBoundary = true
// 将仿真行为添加到仿真器中
self.animator.addBehavior(gravityBehavior)
self.animator.addBehavior(collisionBehavior)
}
// 重力行为,view会直接掉下来不见掉
func gravity()
{
// 创建仿真器并指定仿真范围,但是直接在函数里面创建是不行的,因为这个函数执行完毕之后仿真器就被销毁了
// 创建仿真行为
let behavior = UIGravityBehavior(items: [self.viewA])
// 将仿真行为添加到仿真器中
animator.addBehavior(behavior)
}
}