How to show complete List when keyboard is showing up in SwiftUI

前端 未结 7 576
广开言路
广开言路 2020-12-04 22:30

How is it possible to show the complete List when the keyboard is showing up? The keyboard is hiding the lower part of the list.

I have a textField in my list row. W

7条回答
  •  粉色の甜心
    2020-12-04 23:04

    These examples are a little old, I revamped some code to use the new features recently added to SwiftUI, detailed explanation of the code used in this sample can be found in this article: Article Describing ObservableObject

    Keyboard observer class:

    import SwiftUI
    import Combine
    
    final class KeyboardResponder: ObservableObject {
        let objectWillChange = ObservableObjectPublisher()
        private var _center: NotificationCenter
        @Published var currentHeight: CGFloat = 0
    
        init(center: NotificationCenter = .default) {
            _center = center
            _center.addObserver(self, selector: #selector(keyBoardWillShow(notification:)), name: UIResponder.keyboardWillShowNotification, object: nil)
            _center.addObserver(self, selector: #selector(keyBoardWillHide(notification:)), name: UIResponder.keyboardWillHideNotification, object: nil)
        }
    
        @objc func keyBoardWillShow(notification: Notification) {
            if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
                currentHeight = keyboardSize.height
            }
        }
    
        @objc func keyBoardWillHide(notification: Notification) {
            currentHeight = 0
        }
    }
    

    Usage:

    @ObservedObject private var keyboard = KeyboardResponder()
    
    VStack {
     //Views here
    }
    //Makes it go up, since negative offset
    .offset(y: -self.keyboard.currentHeight)
    

提交回复
热议问题