碰撞迅速拖放

时间:2015-05-29 21:20:46

标签: swift drag-and-drop collision-detection

我是Swift的新手。我试图弄清楚如何拖放和图像到一个盒子上,并检测何时发生碰撞。当我让重力和动画作用于图像时,它会检测到碰撞。但是当我将图像拖到框中时,它没有检测到它。我将不胜感激任何帮助!感谢。

这是我正在尝试使用的代码:

import UIKit
import AVFoundation


class Punc2ViewController: UIViewController, UICollisionBehaviorDelegate {

    var player2:AVAudioPlayer = AVAudioPlayer()
    var error : NSError? = nil
    var location =  CGPoint(x: 0, y: 0)

    var animator: UIDynamicAnimator!
    var gravity: UIGravityBehavior!
    var collision: UICollisionBehavior!


    @IBOutlet weak var period: UIImageView!


    override func viewDidLoad() {
        super.viewDidLoad()

        period.center = CGPointMake(650, 100)
        view.addSubview(period)

        let barrier = UIView(frame: CGRect(x: 600, y: 200, width: 130, height: 20))
        barrier.backgroundColor = UIColor.redColor()
        view.addSubview(barrier)

        animator = UIDynamicAnimator(referenceView: view)
        //gravity = UIGravityBehavior(items: [period])
        //animator.addBehavior(gravity)

        collision = UICollisionBehavior(items: [period])
        collision.collisionDelegate = self
        // add a boundary that has the same frame as the barrier
        collision.addBoundaryWithIdentifier("barrier", forPath: UIBezierPath(rect: barrier.frame))
        collision.translatesReferenceBoundsIntoBoundary = true
        animator.addBehavior(collision)

        collision.action = {


        }
    }

    func collisionBehavior(behavior: UICollisionBehavior!, beganContactForItem item: UIDynamicItem!, withBoundaryIdentifier identifier: NSCopying!, atPoint p: CGPoint) {
        println("Boundary contact occurred - \(identifier)")
    }

    @IBAction func handlePan(recognizer:UIPanGestureRecognizer) {
        let translation = recognizer.translationInView(self.view)
        if let view = recognizer.view {
            view.center = CGPoint(x:view.center.x + translation.x,
                y:view.center.y + translation.y)
        }
        recognizer.setTranslation(CGPointZero, inView: self.view)

    }
}

1 个答案:

答案 0 :(得分:0)

使用

if CGRectIntersectsRect(imageview.frame,imageview2.frame) {
//do something 
}

如果两个对象(它们的框架)相交

,则返回true