Skip to content

Instantly share code, notes, and snippets.

@fahied
Last active December 17, 2019 10:16
Show Gist options
  • Save fahied/dcd1de5a758a9bfa35e11c6e2611137a to your computer and use it in GitHub Desktop.
Save fahied/dcd1de5a758a9bfa35e11c6e2611137a to your computer and use it in GitHub Desktop.
Auto Track Analytics iOS
@objc class AutoTrackedViewController: UIViewController {
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
tracker.trackScreen(name: Self.screenName, className: Self.className)
addTrackingTarget()
}
override func viewDidLoad() {
super.viewDidLoad()
addTrackingTarget()
}
func addTrackingTarget() {
let buttons = view.allSubViewsOf(type: UIButton.self)
buttons.forEach { $0.addTarget(self, action: #selector(self.trackButtonClick(sender:)), for: .touchUpInside) }
}
@objc func trackButtonClick(sender: UIButton) {
let targets = sender.allTargets
for target in targets {
if let actions = sender.actions(forTarget: target, forControlEvent: .touchUpInside) {
for action in actions {
print("taget: \(target) - \(action)")
}
}
}
}
}
extension AutoTrackedViewController {
class var className: String {
return String(describing: self)
}
class var screenName: String {
return ScreenNameProvider.shared.getScreenName(for: self.className)
}
}
extension UIView {
/** This is the function to get subViews of a view of a particular type
*/
func subViews<T : UIView>(type : T.Type) -> [T]{
var all = [T]()
for view in self.subviews {
if let aView = view as? T{
all.append(aView)
}
}
return all
}
/** This is a function to get subViews of a particular type from view recursively. It would look recursively in all subviews and return back the subviews of the type T */
func allSubViewsOf<T : UIView>(type : T.Type) -> [T]{
var all = [T]()
func getSubview(view: UIView) {
if let aView = view as? T{
all.append(aView)
}
guard view.subviews.count>0 else { return }
view.subviews.forEach{ getSubview(view: $0) }
}
getSubview(view: self)
return all
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment