快速检测两个 UIView 的碰撞
Posted
技术标签:
【中文标题】快速检测两个 UIView 的碰撞【英文标题】:Detect collision of two UIView's in swift 【发布时间】:2015-07-23 12:20:59 【问题描述】:我的 ViewController 上有两个 UIView。我将 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)
【问题讨论】:
【参考方案1】:怎么样
if (CGRectIntersectsRect(secondView.frame, sender.frame))
// Do something
CGRectIntersectsRect(::) : 返回两个矩形是否相交。
【讨论】:
【参考方案2】:Swift 3 CGRectIntersectsRect 用相交替换
for collider in colliders
if (collider.frame.intersects(frameTarget))
return
【讨论】:
以上是关于快速检测两个 UIView 的碰撞的主要内容,如果未能解决你的问题,请参考以下文章