作者:不会游泳的小饼儿 | 来源:互联网 | 2023-08-11 15:41
在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))
}
}