我有这个
struct ContentView: View {
var body: some View {
ZStack(alignment: Alignment.bottom) {
List {
Text("Default text").foregroundColor(Color.red)
}
TextField("Placeholder", text: .constant(""))
.frame(minHeight: 30)
.cornerRadius(8.0)
.padding(10)
.background(Color.blue)
}
}
}
实际上,当我专注于 TextField 时,键盘会隐藏此文本字段。
SwiftUI 中是否有一个简单的解决方案来使文本字段始终位于键盘顶部?
最佳答案
这是一个片段,它观察与键盘相关的 NotificationCenter
通知,并根据计算出的键盘高度更改间隔 View 的高度。
import Combine
struct ExampleView: View {
@State var keyboardHeight: CGFloat = 0
var cancellables: Set<AnyCancellable> = []
init() {
NotificationCenter.default.publisher(for: UIResponder.keyboardWillChangeFrameNotification)
.merge(with: NotificationCenter.default.publisher(for: UIResponder.keyboardWillHideNotification))
.compactMap({ notification in
guard let keyboardFrameValue: NSValue = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue else { return nil }
let keyboardFrame = keyboardFrameValue.cgRectValue
// If the rectangle is at the bottom of the screen, set the height to 0.
if keyboardFrame.origin.y == UIScreen.main.bounds.height {
return 0
} else {
// Adjust for safe area
return keyboardFrame.height - (UIApplication.shared.windows.first?.safeAreaInsets.bottom ?? 0)
}
})
.assign(to: \.keyboardHeight, on: self)
.store(in: &cancellables)
}
var body: some View {
VStack {
// Your content here
Spacer()
.frame(height: keyboardHeight)
}
}
}
我写了一个 Swift 包来为您处理这个问题。它公开了一个包装您的内容的 KeyboardObservingView
。
可在此处获得:https://github.com/nickffox/KeyboardObserving
你会像这样使用它:
var body: some View {
KeyboardObservingView {
List {...}
TextField("Placeholder", text: .constant(""))
.frame(minHeight: 30)
.cornerRadius(8.0)
.padding(10)
.background(Color.blue)
}
}
这是正在使用的包的图片: demo
关于ios - 使用 SwiftUI,TextField 始终位于键盘顶部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57497477/