【问题标题】:Track all user touches in the application Swift跟踪应用程序 Swift 中的所有用户触摸
【发布时间】:2020-04-15 00:23:33
【问题描述】:

我在 stackoverflow 上搜索了大约一周,关于我想要跟踪所有用户触摸的问题,但没有成功,我知道有很多这样的问题打开了,但不是我要寻找的具体问题。

我想要的: 跟踪所有用户触摸,例如按下 UIButton 或按下 UITextfield 或打开某些 ViewController 等等。 但是:为什么这个问题不同,我想要一些标签文本来解释按下了哪个确切的按钮,例如,如果我有 LoginVC 并且有登录按钮,我想要方法来解释“ 按下了登录按钮”或“按下了忘记按钮”,然后记录此事件/触摸。

提前致谢!

【问题讨论】:

    标签: ios swift xcode events


    【解决方案1】:

    您可以创建一个 BaseViewController,并在其视图中添加一个点击手势识别器,然后确定哪个子视图被点击,如下所示:

    class BaseViewController: UIViewController {
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(viewDidTap(_:)))
            tapRecognizer.delegate = self
            tapRecognizer.cancelsTouchesInView = false
            self.view.addGestureRecognizer(tapRecognizer)
        }
    
        @objc func viewDidTap(_ recognizer: UITapGestureRecognizer) {
            guard let view = recognizer.view else { return }
    
            let location = recognizer.location(in: view)
            let subview = view.hitTest(location, with: nil)
            self.log(tappedView: subview ?? view)
        }
    
        func log(tappedView: UIView) {
            // do some base job with the tapped view
        }
    
    }
    
    extension BaseViewController: UIGestureRecognizerDelegate {
        func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldBeRequiredToFailBy otherGestureRecognizer: UIGestureRecognizer) -> Bool {
            let location = gestureRecognizer.location(in: self.view)
            guard let textField = self.view.hitTest(location, with: nil) as? UITextField else { return false }
    
            textField.becomeFirstResponder()
            return true
        }
    }
    

    现在您可以扩展其他视图控制器以具有 BaseViewController 的功能并覆盖 log 方法,如下所示:

    class ChildViewController: BaseViewController {
    
        let forgotButton = UIButton()
        let signinButton = UIButton()
    
        override func log(tappedView: UIView) {
            super.log(tappedView: tappedView)
    
            if (tappedView === self.forgotButton) {
                labelLog.text = "Forgot button was tapped"
            } else if (tappedView === self.signinButton) {
                labelLog.text = "Sign In button was tapped"
            }
        }
    }
    

    【讨论】:

    • 感谢您的回复!所以你的意思是把这个方法添加到每个 ViewController 中?
    • 不是viewController本身,而是viewControllers的视图viewController.view
    • 明智之举,我将对其进行测试,如果它按预期工作,则将答案标记为已接受。谢谢
    • 是的,现在它适用于 UIButton,但不适用于 UITextField
    • 现在当我触摸 UITextField 时它会打印出来,但不能在里面输入
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-19
    • 2016-02-02
    相关资源
    最近更新 更多