我在屏幕上添加了2個UIViews,我想檢測它們是否碰撞。如果是這樣,那麼我需要在屏幕上顯示警報。檢測Swift 3.0中的兩個對象的碰撞?
-1
A
回答
0
// 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
}
}
2
您可以通過檢查它們的幀是否相交來檢查是否有相交的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
您可以撥打intersects(_:)
每次更新任何意見幀(即改變它們的大小和/或位置)。如果方法返回true
,請使用UIAlertController
顯示警報。
4
怎麼樣
if (CGRectIntersectsRect(secondView.frame, sender.frame)) {
// Do something
}
相關問題
- 1. 碰撞檢測Swift
- 2. ActionScript 3.0中的矩形碰撞檢測?
- 3. 子視圖中兩個對象之間的碰撞檢測
- 4. Android中兩個對象的碰撞檢測
- 5. CreateJS - 碰撞檢測與多個對象在兩個容器中
- 6. 檢測碰撞SpriteKit Swift
- 7. Sprite套件中的碰撞檢測Swift
- 8. 需要幫助檢測兩個對象之間的碰撞
- 9. 碰撞檢測與兩個相同的精靈對象andengine?
- 10. iOS - 如何檢測兩個或多個對象是否碰撞
- 11. Flex 3:碰撞檢測和碰撞後移動對象
- 12. 抽象碰撞檢測
- 13. 地形對象碰撞檢測
- 14. 碰撞檢測:圓角對象
- 15. 檢查java中兩個對象之間的碰撞
- 16. 碰撞檢測
- 17. OOP中的物理碰撞檢測,包含一個對象的兩次迭代
- 18. java中的碰撞檢測
- 19. Unity3D中的碰撞檢測
- 20. Android中的碰撞檢測
- 21. pygame中的碰撞檢測
- 22. paper.js中的碰撞檢測
- 23. cocos2d中的碰撞檢測
- 24. pygame中的碰撞檢測
- 25. SceneKit Swift 2.0碰撞檢測(SCNPhysicsContactDelegate)
- 26. 同一類型的多個對象上的SpriteKit碰撞檢測
- 27. Ellipse2D對象和Arc2d對象之間的碰撞檢測
- 28. 碰撞檢測不檢測
- 29. n體碰撞檢測和成對碰撞檢測之間的區別?
- 30. 碰撞檢測只需添加+1一次不是幾倍的對象碰撞