【问题标题】:How prevent a parent UIView to receive touch from UIButton?如何防止父 UIView 接收来自 UIButton 的触摸?
【发布时间】:2017-12-25 09:11:18
【问题描述】:

我有一个 UIView(来自 UIViewController)接收触摸和删除键盘。在同一个屏幕中,我有一个显示密码的 UIButton,当我触摸 UIButton 时,触摸会转到 UIView 并移除键盘。

如何防止 UIView 接收来自 UIButton 的触摸?

我会尝试.isExclusiveTouch,但没有成功。

编辑

移除键盘的我的扩展:

import UIKit

public extension UIViewController {
    func hideKeyboardWhenTappedAround() {
        let tap: UITapGestureRecognizer = UITapGestureRecognizer(
            target: self,
            action: #selector(UIViewController.dismissKeyboard)
        )
        tap.cancelsTouchesInView = false
        view.addGestureRecognizer(tap)
    }

    func dismissKeyboard() {
        view.endEditing(true)
    }
}

在我的 ViewController 中,按钮:

self.myButton.addTarget(self, action: #selector(self.myButtonHandler), for: .touchUpInside)
self.view.addSubview(self.myButton)

【问题讨论】:

  • 你有一些代码可以给我们看吗?它会帮助我们。谢谢!
  • 是的!现在添加问题...
  • @user2921672 我认为您的问题是您的 UITextField 失去焦点,我的意思是它已从第一响应者中删除,这就是键盘被关闭的原因,但这与 UIButton 无关将触摸传递给 superView

标签: ios swift uiview uibutton keyboard


【解决方案1】:

不要使用手势,只需使用此代码

override func touchesBegan(_ touches: Set<UITouch>, with event:UIEvent?) {
    if let touch = touches.first {
        view.endEditing(true)
    }
    super.touchesBegan(touches, with: event)
}

在这里,当您触摸视图的任何部分(不是按钮)时,键盘将被代码关闭(view.endEditing(true))

【讨论】:

    【解决方案2】:

    尝试将 userIntrecationEnabled 设置为 false。

    //example
    yourView.isUserInteractionEnabled = false
    

    如果视图禁用了用户交互,它将忽略触摸。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-17
    • 2011-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多