跟踪应用程序Swift中的所有用户触摸

时间:2018-03-02 12:36:57

标签: ios swift xcode events

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

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

提前致谢!

1 个答案:

答案 0 :(得分:5)

您可以创建一个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"
        }
    }
}