How to write Keyboard notifications in Swift 3

前端 未结 10 1574
清歌不尽
清歌不尽 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:25

    Swift 5.1 + Combine + SwiftUI

    @State var keyboardHeight: CGFloat = 0 // or @Published if one is in ViewModel: ObservableObject
    
    private var cancellableSet: Set = []
        
    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)
        }
        
    

提交回复
热议问题