在 Swift 3.0 中检测碰撞 b/w 两个对象?

Detecting the collision b/w two objects in Swift 3.0?

我在屏幕上添加了 2 个 UIView,我想检测它们是否发生碰撞。如果是这样,那么我需要在屏幕上显示一个警报。

您可以通过检查帧是否相交来检查 2 个视图是否相交。这是一个例子:

let view1 = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
let view2 = UIView(frame: CGRect(x: 90, y: 90, width: 50, height: 50))

extension UIView {
    func intersects(_ otherView: UIView) -> Bool {
        if self === otherView { return false }
        return self.frame.intersects(otherView.frame)
    }
}

print(view1.intersects(view2)) // Prints true because the 2 views are intersecting

每次更新任何视图框架(即更改它们的大小 and/or 位置)时,您都可以调用 intersects(_:)。如果方法 returns true,使用 UIAlertController.

显示警报

怎么样

if (CGRectIntersectsRect(secondView.frame, sender.frame)) {
        // Do something
    }
// The Pan Gesture
func createPanGestureRecognizer(targetView: UIImageView) 
{

    var panGesture = UIPanGestureRecognizer(target: self, action:("handlePanGesture:"))
    targetView.addGestureRecognizer(panGesture)
}

// THE HANDLE

   func handlePanGesture(panGesture: UIPanGestureRecognizer) {


    //        get translation

    var translation = panGesture.translationInView(view)
    panGesture.setTranslation(CGPointZero, inView: view)
    println(translation)


    //create a new Label and give it the parameters of the old one
    var label = panGesture.view as UIImageView
    label.center = CGPoint(x: label.center.x+translation.x, y: label.center.y+translation.y)
    label.multipleTouchEnabled = true
    label.userInteractionEnabled = true

    if panGesture.state == UIGestureRecognizerState.Began {

        //add something you want to happen when the Label Panning has started
    }

    if panGesture.state == UIGestureRecognizerState.Ended {

       //add something you want to happen when the Label Panning has ended

    }


    if panGesture.state == UIGestureRecognizerState.Changed {

    //add something you want to happen when the Label Panning has been change ( during the moving/panning ) 

    }

    else {

       // or something when its not moving
    }

    }