如何在SwiftUI中获取列表交互式键盘的高度?

时间:2019-12-16 23:26:34

标签: swift iphone keyboard uikit swiftui

SwiftUI中,我们可以通过向下滑动使键盘在List中进行交互。我们只需要将此代码提供给视图的init()。

init() {
    UITableView.appearance().keyboardDismissMode = .interactive
}

这可以正常工作,但是附加到键盘的视图不会随键盘本身一起移动。

我发现this个帖子应该可以解决UIKit中的问题。如何在SwiftUI中解决该问题?

这是我处理键盘弹出的方法:

final class KeyboardResponder: ObservableObject {

    private var _center: NotificationCenter
    @Published private(set) var currentHeight: CGFloat = 0
    @Published private(set) var duration: Double = 0.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)
    }

    deinit {
        _center.removeObserver(self)
    }

    @objc func keyBoardWillShow(notification: Notification) {
        if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue,
            let duration = notification.userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as? Double {
            self.duration = duration
            currentHeight = keyboardSize.height
        }
    }

    @objc func keyBoardWillHide(notification: Notification) {
        currentHeight = 0
    }
}

struct KeyboardHandler: ViewModifier {
    let height: CGFloat
    let duration: Double

    func body(content: Content) -> some View {
        content
            .padding(.bottom, height)
            .animation(.spring(blendDuration: duration))
    }
}

0 个答案:

没有答案