Deselect UIView "button" when dragging finger off of it

时间:2018-07-25 04:22:29

标签: ios swift uiview uibutton

I have a UIView that I added a UILongPressGestureRecognizer to so that I can handle clicks and have that UIView work like a button.

let longPressGtr = UILongPressGestureRecognizer(target: self, action:#selector(longPressSelector))
longPressGtr.minimumPressDuration = 0.1
myView.isUserInteractionEnabled = true
myView.addGestureRecognizer(longPressGtr)


@objc func longPressSelector(_ gestureRecognizer: UILongPressGestureRecognizer) {
    if gestureRecognizer.state == .began {
        myView.backgroundColor = UIColor.gray
    } else if gestureRecognizer.state == .ended {
        myView.backgroundColor = UIColor.blue // my button is blue
        doSomething()
    }
}

func doSomething() {
    print("view was pressed")
}

This works, but the one thing that doesn't is when I press and hold on my UIView but drag my finger off the view, the "button" doesn't unselect. It still fires doSomething(). A regular UIButton will deselect the button and not fire it's onClick if you are holding down on it an drag your finger off the view.

How can I implement this functionality into my UIView?

Or is there a better way to make a UIView act like a button?

4 个答案:

答案 0 :(得分:1)

您需要检查手势是否在视图内。

@objc func longPresserDidFire(_ presser: UILongPressGestureRecognizer) {
    let gestureIsInside = myView.point(inside: presser.location(in: myView), with: nil)
    switch presser.state {
    case .began, .changed:
        if gestureIsInside {
            myView.backgroundColor = .blue
        } else {
            myView.backgroundColor = .gray
        }
    case .cancelled:
        myView.backgroundColor = .gray
    case .ended:
        myView.backgroundColor = .gray
        if gestureIsInside {
            doSomething()
        }
    default: break
    }
}

答案 1 :(得分:0)

当您将手指拖到视图之外时,gestureRecognizer可能会转换为failedcancelled状态,因此您需要添加对此情况的处理gestureRecognizer.state == .failedgestureRecognizer.state == .cancelled

答案 2 :(得分:0)

您没有添加peerRecognizer状态更改的条件,这就是它接受结束状态的原因。

@objc func longPressSelector(_ gestureRecognizer: UILongPressGestureRecognizer) {
    if gestureRecognizer.state == .began {

    } else if gestureRecognizer.state == .changed {

    }else if gestureRecognizer.state == .ended {

    }
}

再添加一个条件并检查其是否有效。

答案 3 :(得分:-1)

@objc func longPressSelector(_ gestureRecognizer: UILongPressGestureRecognizer) {

}

Place UILongPressGestureRecognizer instead of UITapGestureRecognizer and check it