使用SwiftUI始终将TextField放在键盘顶部 [英] TextField always on keyboard top with SwiftUI
问题描述
我有这个
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时,键盘会隐藏该文本字段.
Actually, when i focus on the TextField, keyboard hide this textfield.
SwiftUI中是否有一个简单的解决方案可以使文本字段始终位于键盘的顶部?
Is there a simple solution in SwiftUI to keep the textfield always on keyboard's top ?
推荐答案
此处是一个片段,用于观察与键盘相关的 NotificationCenter
通知,并根据计算出的键盘高度更改间隔视图的高度
Here is a snippet that observes NotificationCenter
notifications related the keyboard, and changes the height of a spacer view based on the computed keyboard height.
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
来包装您的内容.
I wrote a Swift package that handles this for you. It exposes a KeyboardObservingView
that wraps your content.
可在此处使用: 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)
}
}
这是正在使用的包装的图像:演示
Here's an image of the package in use: demo
这篇关于使用SwiftUI始终将TextField放在键盘顶部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!