Swift 3 protocol extension using selector error

前端 未结 7 1201
心在旅途
心在旅途 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:53

    Matt's answer is correct. However, I would just add that, if you are dealing with #selector to use from a NotificationCenter notification, you could try to avoid #selector by using the closure version.

    Example:

    Instead of writing:

    extension KeyboardHandler where Self: UIViewController {
    
        func startObservingKeyboardChanges() {
    
            NotificationCenter.default.addObserver(
                self,
                selector: #selector(keyboardWillShow(_:)),
                // !!!!!            
                // compile error: cannot be included in a Swift protocol
                name: .UIKeyboardWillShow,
                object: nil
            )
        }
    
         func keyboardWillShow(_ notification: Notification) {
           // do stuff
        }
    }
    

    you could write:

    extension KeyboardHandler where Self: UIViewController {
    
        func startObservingKeyboardChanges() {
    
            // NotificationCenter observers
            NotificationCenter.default.addObserver(forName: .UIKeyboardWillShow, object: nil, queue: nil) { [weak self] notification in
                self?.keyboardWillShow(notification)
            }
        }
    
        func keyboardWillShow(_ notification: Notification) {
           // do stuff
        }
    }
    
    0 讨论(0)
提交回复
热议问题