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

前端 未结 7 573
广开言路
广开言路 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:01

    Have an observer set an EnvironmentValue. Then make that a variable in your View:

     @Environment(\.keyboardHeight) var keyboardHeight: CGFloat
    
    import SwiftUI
    import UIKit
    
    extension EnvironmentValues {
    
      var keyboardHeight : CGFloat {
        get { EnvironmentObserver.shared.keyboardHeight }
      }
    
    }
    
    class EnvironmentObserver {
    
      static let shared = EnvironmentObserver()
    
      var keyboardHeight: CGFloat = 0 {
        didSet { print("Keyboard height \(keyboardHeight)") }
      }
    
      init() {
    
        // MARK: Keyboard Events
    
        NotificationCenter.default.addObserver(forName: UIResponder.keyboardDidHideNotification, object: nil, queue: OperationQueue.main) { [weak self ] (notification) in
          self?.keyboardHeight = 0
        }
    
        let handler: (Notification) -> Void = { [weak self] notification in
            guard let userInfo = notification.userInfo else { return }
            guard let frame = userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect else { return }
    
            // From Apple docs:
            // The rectangle contained in the UIKeyboardFrameBeginUserInfoKey and UIKeyboardFrameEndUserInfoKey properties of the userInfo dictionary should be used only for the size information it contains. Do not use the origin of the rectangle (which is always {0.0, 0.0}) in rectangle-intersection operations. Because the keyboard is animated into position, the actual bounding rectangle of the keyboard changes over time.
    
            self?.keyboardHeight = frame.size.height
        }
    
        NotificationCenter.default.addObserver(forName: UIResponder.keyboardDidShowNotification, object: nil, queue: OperationQueue.main, using: handler)
    
        NotificationCenter.default.addObserver(forName: UIResponder.keyboardDidChangeFrameNotification, object: nil, queue: OperationQueue.main, using: handler)
    
      }
    

提交回复
热议问题