【发布时间】:2019-09-01 12:28:57
【问题描述】:
以下代码获取键盘显示时的键盘高度,并将按钮移动键盘高度。
在转换源(ContentView)和转换目标(SecibdContentView)以相同的方式执行此移动,但按钮不会在转换目标处移动。
如何使按钮在多个屏幕上移动相同?
import SwiftUI
struct ContentView: View {
@ObservedObject private var keyboard = KeyboardResponder()
var body: some View {
NavigationView {
VStack {
Text("ContentView")
Spacer()
NavigationLink(destination: SecondContentView()) {
Text("Next")
}
.offset(x: 0, y: -keyboard.currentHeight)
}
}
}
}
import SwiftUI
struct SecondContentView: View {
@ObservedObject private var keyboard = KeyboardResponder()
var body: some View {
VStack {
Text("SubContentView")
Spacer()
NavigationLink(destination: ThirdContentView()) {
Text("Next")
}
.offset(x: 0, y: -keyboard.currentHeight)
}
}
}
class KeyboardResponder: ObservableObject {
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)
}
deinit {
_center.removeObserver(self)
}
@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
}
}
【问题讨论】:
-
在模拟器上试过了,真是个解决办法。很遗憾看到 SwiftUI 不能原生处理这个问题。还是我错过了什么?
标签: ios swift iphone swiftui xcode11