問題描述
我正在創建一個類似于 Flappy Bird 的游戲,但用戶將手指放在屏幕上并躲避障礙物,而不是點擊讓小鳥飛起來.
I am creating a game, similar to Flappy Bird but the user holds their finger on the screen and dodges the obstacles, rather than tapping to make the bird fly.
我通過一個 UIScrollView 來做到這一點,其中 UIView 被用作障礙物.當用戶觸摸 UIView 時,游戲結束.
I am doing this by having a UIScrollView, in which UIView's are used as obstacles. When the user touches a UIView, the game is over.
如何從 UIScrollView 中檢測用戶對 UIView 的觸摸?我正在使用帶有 Xcode Beta 4 的 Swift.
How do I detect the users touch of a UIView from within a UIScrollView? I am using Swift with Xcode Beta 4.
這是游戲截圖
如您所見,用戶在向上滾動時在灰色塊 (UIView) 之間移動手指.
As you can see, the user moves their finger between the grey blocks (UIViews) as they scroll up.
推薦答案
通過將滾動視圖的 userInteractionEnabled
設置為 NO
,視圖控制器將開始接收觸摸事件UIViewController
是 UIResponder
的子類.您可以在視圖控制器中覆蓋這些方法中的一個或多個以響應這些觸摸:
By setting userInteractionEnabled
to NO
for your scroll view, the view controller will start receiving touch events since UIViewController
is a subclass of UIResponder
. You can override one or more of these methods in your view controller to respond to these touches:
- touchesBegan: withEvent:
- touchesMoved: withEvent:
- touchesEnded: withEvent:
- touchesCancelled: withEvent:
我創建了一些示例代碼來演示如何做到這一點:
I created some example code to demonstrate how you could do this:
class ViewController: UIViewController {
@IBOutlet weak var scrollView: UIScrollView!
// This array keeps track of all obstacle views
var obstacleViews : [UIView] = []
override func viewDidLoad() {
super.viewDidLoad()
// Create an obstacle view and add it to the scroll view for testing purposes
let obstacleView = UIView(frame: CGRectMake(100,100,100,100))
obstacleView.backgroundColor = UIColor.redColor()
scrollView.addSubview(obstacleView)
// Add the obstacle view to the array
obstacleViews += obstacleView
}
override func touchesBegan(touches: NSSet!, withEvent event: UIEvent!) {
testTouches(touches)
}
override func touchesMoved(touches: NSSet!, withEvent event: UIEvent!) {
testTouches(touches)
}
func testTouches(touches: NSSet!) {
// Get the first touch and its location in this view controller's view coordinate system
let touch = touches.allObjects[0] as UITouch
let touchLocation = touch.locationInView(self.view)
for obstacleView in obstacleViews {
// Convert the location of the obstacle view to this view controller's view coordinate system
let obstacleViewFrame = self.view.convertRect(obstacleView.frame, fromView: obstacleView.superview)
// Check if the touch is inside the obstacle view
if CGRectContainsPoint(obstacleViewFrame, touchLocation) {
println("Game over!")
}
}
}
}
這篇關于Xcode &Swift - 在 UIScrollView 內檢測 UIView 的用戶觸摸的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!