我的ViewController上有两个UIViews。我将panGesture添加到第一个视图,当我开始移动此视图时,第二个视图将移向第一个视图。我希望在这两个视图发生碰撞时检测到一个事件。这是我的代码。
@IBAction func dragFirstView(sender: UIPanGestureRecognizer) {
let translation = sender.translationInView(self.view)
dispatch_async(dispatch_get_main_queue()) { () -> Void in
UIView.animateWithDuration(2.5, delay: 0.0, options: UIViewAnimationOptions.CurveEaseOut, animations: {
self.secondView.frame = CGRectMake(sender.view!.center.x + translation.x, sender.view!.center.y + translation.y, self.secondView.frame.size.width, self.secondView.frame.size.height)
}, completion: nil)
}
sender.view!.center = CGPoint(x: sender.view!.center.x + translation.x, y: sender.view!.center.y + translation.y)
sender.setTranslation(CGPointZero, inView: self.view)
}
答案 0 :(得分:9)
怎么样
if (CGRectIntersectsRect(secondView.frame, sender.frame)) {
// Do something
}
CGRectIntersectsRect(::):返回两个矩形是否相交。
答案 1 :(得分:7)
Swift 3 CGRectIntersectsRect替换为intersects
for collider in colliders
{
if (collider.frame.intersects(frameTarget)) {
return
}
}