Xcode & Swift - UIScrollView 内の UIView のユーザータッチを検出する 質問する

Xcode & Swift - UIScrollView 内の UIView のユーザータッチを検出する 質問する

私は Flappy Bird に似たゲームを作成していますが、ユーザーはタップして鳥を飛ばすのではなく、画面上で指を保持して障害物を回避します。

私は UIScrollView を使ってこれを実現しています。UIScrollView では UIView が障害物として使用されます。ユーザーが UIView に触れると、ゲームは終了します。

UIScrollView 内から UIView のユーザータッチを検出するにはどうすればよいですか? Xcode Beta 4 で Swift を使用しています。

編集:これはゲームのスクリーンショットです

これはゲームのスクリーンショットです

ご覧のとおり、ユーザーは上にスクロールしながら灰色のブロック (UIViews) 間で指を動かします。

ベストアンサー1

userInteractionEnabledスクロール ビューをに設定すると、は のサブクラスであるNOため、ビュー コントローラはタッチ イベントの受信を開始します。ビュー コントローラでこれらのメソッドの 1 つ以上をオーバーライドして、これらのタッチに応答できます。UIViewControllerUIResponder

  • タッチ開始: イベントあり:
  • タッチ移動: イベントあり:
  • タッチ終了: イベントあり:
  • タッチキャンセル: イベントあり:

これを実行する方法を示すサンプル コードをいくつか作成しました。

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!")
            }
        }
    }

}

おすすめ記事