How to get the keyboard height on multiple screens with SwiftUI and move the button

后端 未结 3 579
不知归路
不知归路 2021-02-09 02:22

The following code gets the keyboard height when the keyboard is displayed and moves the button by the keyboard height.

This movement is performed in the same way at the

3条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-09 02:57

    SwiftUI + Combine

    @Published var keyboardHeight: CGFloat = 0 // if one is in ViewModel: ObservableObject
    
    private var cancellableSet: Set = []
        
    init() {
            
         NotificationCenter.default.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.default.publisher(for: UIWindow.keyboardDidHideNotification)
             .map { _ in 0 }
             .assign(to: \.keyboardHeight, on: self)
             .store(in: &cancellableSet)
        }
        
    

提交回复
热议问题