Can I swizzle didSelectRowAtIndexPath: of UITableViewDelegate?

后端 未结 1 463
青春惊慌失措
青春惊慌失措 2021-02-10 14:04

The problem is this:

I need to be able to get analytics on didSelectRowAtIndexPath throughout a big existing app with lots of tableViews.

My first thought of t

1条回答
  •  终归单人心
    2021-02-10 14:18

    It might be late for giving answer, but hopefully it will help some other developer. Below link have help me a lot.

    https://www.jianshu.com/p/9a93ae99fb27

       extension UITableView {
    
            @objc static func swizzleTableView() {
    
              guard self == UITableView.self else {
                return
              }
    
              let originalTableViewDelegateSelector = #selector(setter: self.delegate)
              let swizzledTableViewDelegateSelector = #selector(self.nsh_set(delegate:))
    
              let originalTableViewMethod = class_getInstanceMethod(self, originalTableViewDelegateSelector)
              let swizzledTableViewMethod = class_getInstanceMethod(self, swizzledTableViewDelegateSelector)
    
              method_exchangeImplementations(originalTableViewMethod!,
                                             swizzledTableViewMethod!)
            }
    
            @objc open func nsh_set(delegate: UITableViewDelegate?) {
              nsh_set(delegate: delegate)
    
              guard let delegate =  delegate else { return }
    
              let originalDidSelectSelector = #selector(delegate.tableView(_:didSelectRowAt:))
              let swizzleDidSelectSelector = #selector(self.tableView(_:didSelectRowAt:))
    
              let swizzleMethod = class_getInstanceMethod(UITableView.self, swizzleDidSelectSelector)
              let didAddMethod = class_addMethod(type(of: delegate), swizzleDidSelectSelector, method_getImplementation(swizzleMethod!), method_getTypeEncoding(swizzleMethod!))
    
              if didAddMethod {
                let didSelectOriginalMethod = class_getInstanceMethod(type(of: delegate), NSSelectorFromString("tableView:didSelectRowAt:"))
                let didSelectSwizzledMethod = class_getInstanceMethod(type(of: delegate), originalDidSelectSelector)
                if didSelectOriginalMethod != nil && didSelectSwizzledMethod != nil {
                  method_exchangeImplementations(didSelectOriginalMethod!, didSelectSwizzledMethod!)
                }
              }
          }
    
          @objc open func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
            self.tableView(tableView, didSelectRowAt: indexPath)
    
          }
        }
    

    0 讨论(0)
提交回复
热议问题