UIPinchGestureRecognizer

UIPinchGestureRecognizer

使用UIPinchGestureRecognizer时,分别检测/读取水平和垂直方向上的收缩秤的最佳方法是什么?我看到了这个帖子

UIPinchGestureRecognizer Scale view in different x and y directions

但我注意到执行如此看似例行的任务的来回次数很多,因此我不确定这是否是最佳答案。

如果完全不使用UIPinchGestureRecognizer来解决此问题,那么在两个不同方向上检测收缩比例的最佳方法是什么?

最佳答案

基本上是这样

func _mode(_ sender: UIPinchGestureRecognizer)->String {

    // very important:
    if sender.numberOfTouches < 2 {
        print("avoided an obscure crash!!")
        return ""
    }

    let A = sender.location(ofTouch: 0, in: self.view)
    let B = sender.location(ofTouch: 1, in: self.view)

    let xD = fabs( A.x - B.x )
    let yD = fabs( A.y - B.y )
    if (xD == 0) { return "V" }
    if (yD == 0) { return "H" }
    let ratio = xD / yD
    // print(ratio)
    if (ratio > 2) { return "H" }
    if (ratio < 0.5) { return "V" }
    return "D"
}

该函数将为您返回H,V,D ..水平,垂直,对角线。

你会用这样的东西...
func yourSelector(_ sender: UIPinchGestureRecognizer) {

    // your usual code such as ..
    // if sender.state == .ended { return } .. etc

    let mode = _mode(sender)
    print("the mode is \(mode) !!!")

    // in this example, we only care about horizontal pinches...
    if mode != "H" { return }

    let vel = sender.velocity
    if vel < 0 {
        print("you're squeezing the screen!")
    }
}

07-28 03:56