[英]Track all user touches in the application Swift
我在 stackoverflow 上搜索了大約一個星期,關於我想跟蹤所有用戶觸摸的問題,但沒有成功,我知道有很多這樣打開的問題,但不是我正在尋找的具體問題。
我想要的:跟蹤所有用戶觸摸,包括例如按下 UIButton 或按下 UITextfield 或打開某些 ViewController 等等。 但是:為什么這個問題不同,我想要一些標簽文本來解釋按下了哪個按鈕,例如,如果我有 LoginVC 並且有登錄按鈕,我想要方法來解釋“按下登錄按鈕”或“忘記按下按鈕”然后記錄此事件/觸摸。
提前致謝!
您可以創建一個 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"
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.