UITapGestureRecognizer 未在 Swift 3 中触发

UITapGestureRecognizer not firing in Swift 3

我在自定义 UIViewController 中有以下代码:

let tapDismissTextField = UITapGestureRecognizer(target: self, action: #selector(dismissTap))

func dismissTap() {

    print("Tap!")
}

override func viewDidLoad() {
    super.viewDidLoad()

    self.view.addGestureRecognizer(tapDismissTextField)
    self.friendsView.addGestureRecognizer(tapDismissTextField)
}

未打印 "Tap!" 行,因此手势识别器未触发。可能出了什么问题?

在此控制器中的所有视图中,启用用户交互是 true

如果有任何帮助,此视图控制器已嵌入 UINavigationController

您只需在加载视图后分配 self。

var tapDismissTextField: UITapGestureRecognizer!

并在您的 viewDidLoad 方法中:

override func viewDidLoad() {
    super.viewDidLoad()
    tapDismissTextField = UITapGestureRecognizer(target: self, action: #selector(dismissTap))
    view.addGestureRecognizer(tapDismissTextField)
}

1. 移动此行:

let tapDismissTextField = UITapGestureRecognizer(target: self, action: #selector(dismissTap))

viewDidLoad() 内,因为 self 在方法/函数/闭包之外 returns 一个 (NSObject) -> () -> YourClass() (一个 NSObject),而不是你的 class,它实际上是 view.

的所有者

2. 我建议只留下一个视图 GestureRecognizer

将 tap Dismiss TextField 添加到 viewdidload

override func viewDidLoad() {
    super.viewDidLoad()
 let tapDismissTextField = UITapGestureRecognizer(target: self, action: #selector(dismissTap))
    self.view.addGestureRecognizer(tapDismissTextField)
    self.friendsView.addGestureRecognizer(tapDismissTextField)
}

这不是在 UITextField 上执行操作的正确方法。我猜你确实将 setUserInteraction 更改为 false 以防止 UITextField 行为。正确的?这就是为什么你的手势识别器不起作用。

所以,你需要付出,因为你看到我们现在处于两难境地。我们希望手势起作用,但我们不希望 UITextField 表现正常。我们需要知道您将取得什么成就才能更好地帮助您。

信息:

If you wonna show a custom view. for example UIPickerView set the inputView property for your UITextField and remove your gesture recognizer.

解决方法:

You can use the tap gesture on UITextField superview. And, try to detect if the tap is inside the frame of the UITextField. example

另一种解决方法:

Try to do your action on the textFieldDidBeginEditting delegate method. And do some tweaks to disable the keyboard. may be setting the inputView to nil.

所以,我们需要确切地知道您想要达到什么目的才能为您提供合适的解决方案。