swift 快速奔跑的兔几 本节的内容是:重力和snap效果

前端之家收集整理的这篇文章主要介绍了swift 快速奔跑的兔几 本节的内容是:重力和snap效果前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

本例的运行结果是一个图片可以自由落下,点击鼠标第一次,图片粘附到鼠标点击的位置,点击鼠标第二次,图片自由落下,重复该过程。

需要注意的是,gravity和snap会又些冲突,所以需要以下这一行代码

dynamicAnimator.removeAllBehaviors()
import UIKit

class ViewController: UIViewController {

    @IBAction func tapped(sender: AnyObject) {
        let tap = sender as! UITapGestureRecognizer
        
        if tap.state == UIGestureRecognizerState.Ended{
            let point = tap.locationInView(tap.view)
            //print(point)
            self.snap = UISnapBehavior(item: self.dynamicImageView,snapToPoint: point)
            if (snap != nil){
                dynamicAnimator.removeAllBehaviors()
                dynamicAnimator.addBehavior(self.snap!)
                if fall==0{
                    fall=1
                }else{
                    addBehaviorSelf()
                    fall=0
                }
            }
        }
    }
    @IBOutlet weak var dynamicImageView: UIImageView!
    
    var fall = 0
    
    var dynamicAnimator = UIDynamicAnimator()
    var snap: UISnapBehavior?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let img1 = UIImage(named:"littleYellowMan.jpg")
        dynamicImageView.image = img1
        
        dynamicAnimator = UIDynamicAnimator(referenceView: self.view)
        addBehaviorSelf()
        
    }

    func addBehaviorSelf(){
        dynamicAnimator.removeAllBehaviors()
        
        let gravityBehavior = UIGravityBehavior(items: [self.dynamicImageView])
        dynamicAnimator.addBehavior(gravityBehavior)
        
        let collisionBehavior = UICollisionBehavior(items: [self.dynamicImageView])
        collisionBehavior.translatesReferenceBoundsIntoBoundary = true
        dynamicAnimator.addBehavior(collisionBehavior)
    }
}
原文链接:https://www.f2er.com/swift/325516.html

猜你在找的Swift相关文章