How to write Keyboard notifications in Swift 3

前端 未结 10 1564
清歌不尽
清歌不尽 2020-12-08 10:37

I\'m trying to update this code to swift 3:

NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector(\"keyboardWillShow:\"), name: UIKeyboar         


        
相关标签:
10条回答
  • 2020-12-08 11:22

    For Swift 4.2 .UIKeyboardWillShow is renamed to UIResponder.keyboardWillShowNotification and .UIKeyboardWillHide is renamed to 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
        }
    
    0 讨论(0)
  • 2020-12-08 11:25

    Swift 5.1 + Combine + 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)
        }
        
    
    0 讨论(0)
  • 2020-12-08 11:32
      NotificationCenter.default.addObserver(self, selector: Selector(("keyboardWillShow:")), name:UIResponder.keyboardWillShowNotification, object: nil);
        NotificationCenter.default.addObserver(self, selector: Selector(("keyboardWillHide:")), name:UIResponder.keyboardWillHideNotification, object: nil);
    
    0 讨论(0)
  • 2020-12-08 11:33

    You can perform keyboard notification on both version of Swift respectively.

    Add Objserver:

    NotificationCenter.default.addObserver(self, selector: #selector(keyboardDidShow), name: .UIKeyboardWillShow, object: nil)
    

    Call function swift 3

    func keyboardDidShow() {
              print("keyboardDidShow")
           }
    

    Call function In swift 4

    @objc func keyboardDidShow() {
          print("keyboardDidShow")
       }
    
    0 讨论(0)
提交回复
热议问题