Swift 3 protocol extension using selector error

前端 未结 7 1207
心在旅途
心在旅途 2020-12-15 04:51

I have what I thought to be a very simple protocol extension for my UIViewControllers providing the capability to dismiss a keyboard through a tap gesture. Here

7条回答
  •  天涯浪人
    2020-12-15 05:38

    Here is a similar use-case, you can call a method through a selector without using @objc as in swift by using the dynamic keyword. By doing so, you are instructing the compiler to use dynamic dispatch implicitly.

    import UIKit
    
    protocol Refreshable: class {
    
        dynamic func refreshTableData()
    
        var tableView: UITableView! {get set}
    }
    
    extension Refreshable where Self: UIViewController {
    
        func addRefreshControl() {
            tableView.insertSubview(refreshControl, at: 0)
        }
    
        var refreshControl: UIRefreshControl {
            get {
                let tmpAddress = String(format: "%p", unsafeBitCast(self, to: Int.self))
                if let control = _refreshControl[tmpAddress] as? UIRefreshControl {
                    return control
                } else {
                    let control = UIRefreshControl()
                    control.addTarget(self, action: Selector(("refreshTableData")), for: .valueChanged)
                    _refreshControl[tmpAddress] = control
                    return control
                }
            }
        }
    }
    
    fileprivate var _refreshControl = [String: AnyObject]()
    
    class ViewController: UIViewController: Refreshable {
        @IBOutlet weak var tableView: UITableView! {
            didSet {
                addRefreshControl()
            }
        }
    
        func refreshTableData() {
            // Perform some stuff
        }
    }
    

提交回复
热议问题