Swift4转Swift5报错:ViewController无keyboardDidShow(notification:)成员
Hey there! Let's fix this Swift 5 migration error step by step. That error pops up because the compiler can't locate your keyboardDidShow(notification:) method when registering the notification observer, and there are a few common culprits in Swift 5:
1. Ensure Your Method Has the Right Access & Decorator
Swift 5 is stricter about exposing methods to Objective-C (since NotificationCenter relies on Objective-C runtime for selectors). Make sure your keyboardDidShow method is marked with @objc and has an accessible scope (default internal works, avoid private unless necessary):
@objc func keyboardDidShow(notification: NSNotification) { // Your keyboard handling logic here }
Pro tip: If you prefer using Swift's native Notification type instead of NSNotification, that's fine too—just keep the selector and method signature matched:
@objc func keyboardDidShow(notification: Notification) { // Same logic applies }
2. Check for Extension Scope Issues
If you've defined keyboardDidShow inside an extension of ViewController, you need to explicitly mark the method (or the entire extension) with @objc so the Objective-C runtime can find it:
extension ViewController { @objc func keyboardDidShow(notification: NSNotification) { // Your code here } }
3. Verify Selector & Method Name Match
Double-check for typos! Even a tiny mismatch (like keyboardDidShowNotification instead of keyboardDidShow) will trigger this error. Ensure the name inside #selector() exactly matches your method's name and parameter label.
4. Try the Safer Closure-Based Notification Syntax (Swift 5+)
To avoid selector-related headaches entirely, use Swift 5's preferred closure-based NotificationCenter API. No @objc needed, and it eliminates signature mismatch risks:
override func viewDidLoad() { super.viewDidLoad() NotificationCenter.default.addObserver(forName: UIResponder.keyboardDidShowNotification, object: nil, queue: .main) { [weak self] notification in guard let self = self else { return } if let keyboardFrame = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect { print("Keyboard height: \(keyboardFrame.height)") // Adjust your layout here } } }
Here's a complete snippet to reference:
class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Register the notification observer NotificationCenter.default.addObserver(self, selector: #selector(keyboardDidShow(notification:)), name: UIResponder.keyboardDidShowNotification, object: nil) } @objc func keyboardDidShow(notification: NSNotification) { if let keyboardFrame = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect { // Update your UI to account for the keyboard print("Keyboard appeared with height: \(keyboardFrame.height)") } } // Clean up observer (optional for iOS 9+, but good practice) deinit { NotificationCenter.default.removeObserver(self) } }
内容的提问来源于stack exchange,提问作者user11721027

