快速检测屏幕左侧和右侧的触摸SKScene

时间:2017-02-28 00:05:19

标签: ios swift skscene touches

我正在尝试检测用户是否在SKScene中触摸屏幕的左侧或右侧。

我已将以下代码放在一起,但无论触摸的位置如何,它都只输出“正确”。

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {



    for touch in touches {
        let location = touch.location(in: self)

        if(location.x > self.frame.size.width/2){
            print("Left")
        }

        else if(location.x < self.frame.size.width/2){
            print("Right")
        }
    }
}

2 个答案:

答案 0 :(得分:0)

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

    for touch in touches {
        let location = touch.location(in: self)

        if(location.x < 0){
            print("Left")
        }  
        else {
            print("Right")
        }
    }
}

这似乎有效。在您检查触摸是否位于屏幕左侧的左侧/右侧之前,它总是给您正确的。例如,在iPhone 7 plus上,您将检查您的触摸(让x表示x为20)是否位于365左侧的右侧。由于20小于365,它说你点击了右侧。

答案 1 :(得分:0)

对于 Swift 5.0

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

    let touch = touches.first
    if let location = touch?.location(in: UIScreen.main.focusedView) {
        let halfScreenWidth = UIScreen.main.bounds.width / 2
        if location.x < halfScreenWidth {
            print("Left touch")
            //Your actions when you click on the left side of the screen
        } else {
            print("Right touch")
            // Your actions when you click on the right side of the screen
        }
    }
}

Gesture Recognizer 的另一种方法(该方法解决了滑动和点击之间的冲突)

override func viewDidLoad() {
    tapObserver() 
}

private func tapObserver() {
    let tapGestureRecongnizer = UITapGestureRecognizer(target: self, action: #selector(executeTap))
    tapGestureRecongnizer.delegate = self
    view.addGestureRecognizer(tapGestureRecongnizer)
}

@objc func executeTap(tap: UITapGestureRecognizer) {
    let point = tap.location(in: self.view)
    let leftArea = CGRect(x: 0, y: 0, width: view.bounds.width/2, height: view.bounds.height)
    if leftArea.contains(point) {
        print("Left tapped")
        //Your actions when you click on the left side of the screen
    } else {
        print("Right tapped")
        //Your actions when you click on the right side of the screen
    }
}