2017-02-18 41 views

回答

0

如果你只在鍵盤的高度興趣,你可以觀察UIKeyboardDidChangeFrame通知

let keyboardHeight = NotificationCenter.default.rx 
    .notification(NSNotification.Name.UIKeyboardDidChangeFrame) 
    .map { notification -> CGFloat in 
    (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue.height ?? 0 
    } 

注那些鍵盤的高度即使在離開屏幕時也會保持「完整」。這些通知僅對由於鍵盤語言更改或顯示/隱藏自動完成按鈕而導致的幀更改感興趣。

如果您想知道鍵盤的框架在屏幕上時爲0,則可以將上述可觀察事件與UIKeyboardWillShowUIKeyboardHide通知結合使用。

enum KeyboardState { 
    case onScreen 
    case offScreen 
} 

let keyboardOnScreenHeight = Observable.from([ 
    NotificationCenter.default.rx.notification(NSNotification.Name.UIKeyboardWillShow) 
    .map { _ in KeyboardState.onScreen } 
    NotificationCenter.default.rx.notification(NSNotification.Name.UIKeyboardWillHide) 
    .map { _ in KeyboardState.offScreen } 
]) 
.merge() 
.flatMapLatest { state in 
    switch state { 
    case .onScreen: keyboardHeight 
    case .offScreen: .just(0) 
    } 
} 

從此,您將獲得由先前發出的值定義keyboardHeight當它是在屏幕上,而0時,它退出了。