Search code examples
iosswiftxcodeuiviewtouch

How get count number of touches/actions in my total app by end user in swift


I want to get all touches and buttons actions count in my app to show in UI like how many actions done sofar by user. It's a Swift app.

I tried with following code:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        UtilityClass.sharedInstance.touchesCount += 1
        print(UtilityClass.sharedInstance.touchesCount)
    }

But it's calling only UIView touches events, but not calling for UIButton actions, is there any other solutions to achieve my requirement.

If its single button action, I can call this integer to increase, but, I have number of button actions in my app, thats why I am posting this here.


Solution

  • Try add this to your project

    extension UIButton {
        open override func sendAction(_ action: Selector, to target: Any?, for event: UIEvent?) {
            super.sendAction(action, to: target, for: event)
            UtilityClass.sharedInstance.touchesCount += 1
            print(UtilityClass.sharedInstance.touchesCount)
        }
    }
    

    edit:

    class ViewController: UIViewController {
        @IBAction func buttonAction(_ sender: Any) {
        }
    }
    extension UIButton {
        open override func sendAction(_ action: Selector, to target: Any?, for event: UIEvent?) {
            super.sendAction(action, to: target, for: event)
            print("1111")
        }
    }
    

    above is my full test code, I have a outlet button which is UIButton, every time I click the button action, it will print 1111, and if your button class is custom subclass of UIButton, please change extension UIButton { to extension YourCustomButtonName {