如何在Swift 3中编写键盘通知

Dav*_*nte 19 nsnotificationcenter ios swift swift3

我正在尝试将此代码更新为swift 3:

NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillShow:"), name: UIKeyboardWillShowNotification, object: nil)

NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHide:"), name: UIKeyboardWillHideNotification, object: nil)`
Run Code Online (Sandbox Code Playgroud)

到目前为止,我刚刚尝试了编译器给出的自动更正.这导致代码如下:

let notificationCenter = NotificationCenter.default()
notificationCenter.addObserver(self, selector: Selector(("keyboardWillShow:")), name: NSNotification.Name.UIKeyboardWillShow, object: nil)

notificationCenter.addObserver(self, selector: Selector(("keyboardWillHide:")), name: NSNotification.Name.UIKeyboardWillHide, object: nil)`
Run Code Online (Sandbox Code Playgroud)

不幸的是,这并没有让我走得太远,导致额外的错误.

有人解决了吗?

请注意,我只是在尝试编写通知.我还没(尝试)修复通知功能..谢谢

fss*_*lva 28

Swift 4.2 Xcode 10(10L213o)

与Swift 3相比的主要变化是UIWindow.keyboardWillShowNotificationUIWindow.keyboardWillHideNotification

let notifier = NotificationCenter.default
notifier.addObserver(self,
                     selector: #selector(KeyboardLayoutConstraint.keyboardWillShowNotification(_:)),
                     name: UIWindow.keyboardWillShowNotification,
                     object: nil)
notifier.addObserver(self,
                     selector: #selector(KeyboardLayoutConstraint.keyboardWillHideNotification(_:)),
                     name: UIWindow.keyboardWillHideNotification,
                     object: nil)


@objc
func keyboardWillShowNotification(_ notification: NSNotification) {}

@objc
func keyboardWillHideNotification(_ notification: NSNotification) {}
Run Code Online (Sandbox Code Playgroud)


ZAF*_*007 27

斯威夫特4

override func viewDidLoad() {
    super.viewDidLoad()   
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: .UIKeyboardWillShow, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}

func keyboardWillShow(notification: NSNotification) {
     print("keyboardWillShow")
}

func keyboardWillHide(notification: NSNotification){
     print("keyboardWillHide")
}
Run Code Online (Sandbox Code Playgroud)

你也可以在这些方法内的代码下面获取键盘信息.

NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChange), name: .UIKeyboardWillChangeFrame, object: nil) .      

@objc func keyboardWillChange(notification: NSNotification) {
     let duration = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! Double
     let curve = notification.userInfo![UIKeyboardAnimationCurveUserInfoKey] as! UInt
     let curFrame = (notification.userInfo![UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue
     let targetFrame = (notification.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
     let deltaY = targetFrame.origin.y - curFrame.origin.y
 }
Run Code Online (Sandbox Code Playgroud)

  • 尽管此解决方案有效,但值得一提的是,您需要在 viewWillDisappear 中删除通知观察者以避免内存泄漏。只需添加:`override func viewWillDisappear(_animated: Bool) { super.viewWillDisappear(animated) NotificationCenter.default.removeObserver(self) }` (2认同)

小智 24

我通过编写这样的代码来解决这个问题

NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: .UIKeyboardWillShow, object: nil)
Run Code Online (Sandbox Code Playgroud)


Vig*_*abu 18

对于雨燕4.2 .UIKeyboardWillShow被重命名为UIResponder.keyboardWillShowNotification.UIKeyboardWillHide被重命名为UIResponder.keyboardWillHideNotification

 NotificationCenter.default.addObserver(self, selector: #selector(NameOfSelector), name: UIResponder.keyboardWillShowNotification , object: nil)
 NotificationCenter.default.addObserver(self, selector: #selector(NameOfSelector), name: UIResponder.keyboardWillHideNotification , object: nil)

   @objc func NameOfSelector() {
       //Actions when notification is received
    }
Run Code Online (Sandbox Code Playgroud)


小智 13

您可以使用Selector类型检查#selector(Class.method)对替换已弃用的字符串文字:

let center = NotificationCenter.default
center.addObserver(self,
                   selector: #selector(keyboardWillShow(_:)),
                   name: .UIKeyboardWillShow,
                   object: nil)

center.addObserver(self,
                   selector: #selector(keyboardWillHide(_:)),
                   name: .UIKeyboardWillHide,
                   object: nil)
Run Code Online (Sandbox Code Playgroud)

#selector语法是要安全得多,因为斯威夫特是能够检查在指定的方法确实存在编译时间.

有关Swift选择器的更多信息,请参阅rickster的详细解答.


Ser*_*gey 8

Swift 5.1 + 组合 + SwiftUI

@State var keyboardHeight: CGFloat = 0 // or @Published if one is in ViewModel: ObservableObject

private var cancellableSet: Set<AnyCancellable> = []
    
init() {
            
   let notificationCenter = NotificationCenter.default
        
   notificationCenter.publisher(for: UIWindow.keyboardWillShowNotification)
       .map {
             guard
                 let info = $0.userInfo,
                 let keyboardFrame = info[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect
                 else { return 0 }

             return keyboardFrame.height
         }
         .assign(to: \.keyboardHeight, on: self)
         .store(in: &cancellableSet)
        
     notificationCenter.publisher(for: UIWindow.keyboardDidHideNotification)
         .map { _ in 0 }
         .assign(to: \.keyboardHeight, on: self)
         .store(in: &cancellableSet)
    }
    
Run Code Online (Sandbox Code Playgroud)