SwiftUI 中的键盘管理:全面教程
由 Mux 主办的 DEV 全球展示挑战赛:展示你的项目!
在 iOS 应用中,键盘的外观和行为管理是打造流畅用户体验的关键所在。虽然 SwiftUI 系统会自动处理很多相关事务,但有时您仍然需要更多控制权。我们一直在iOS 应用模板
中运用这些技巧。接下来,我们将深入探讨如何在 SwiftUI 中管理键盘。
1. 键盘操作简介
在 SwiftUI 中,当用户点击某个元素时TextField,系统会自动显示键盘。但是,如果键盘遮挡了该元素TextField或其他重要的 UI 元素,则可能会出现问题。
2. 响应键盘外观
为了控制键盘外观并避免遮挡用户界面,您可以使用keyboardAdaptive()修饰键。但在此之前,您需要注意键盘的高度。
final class KeyboardResponder: ObservableObject {
@Published var currentHeight: CGFloat = 0
var keyboardWillShowNotification = NotificationCenter.default.publisher(for: UIResponder.keyboardWillShowNotification)
var keyboardWillHideNotification = NotificationCenter.default.publisher(for: UIResponder.keyboardWillHideNotification)
init() {
keyboardWillShowNotification.map { notification in
CGFloat((notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect)?.height ?? 0)
}
.assign(to: \.currentHeight, on: self)
.store(in: &cancellableSet)
keyboardWillHideNotification.map { _ in
CGFloat(0)
}
.assign(to: \.currentHeight, on: self)
.store(in: &cancellableSet)
}
private var cancellableSet: Set<AnyCancellable> = []
}
在这里,我们使用 Combine 的publisher(for:)方法来监听keyboardWillShowNotification和keyboardWillHideNotification通知。
现在,让我们来实现这个keyboardAdaptive修饰符。
struct KeyboardAdaptive: ViewModifier {
@ObservedObject private var keyboard = KeyboardResponder()
func body(content: Content) -> some View {
content
.padding(.bottom, keyboard.currentHeight)
.animation(.easeOut(duration: 0.16))
}
}
用法:
TextField("Enter text", text: $inputText)
.modifier(KeyboardAdaptive())
3. 使用 SwiftUI 键盘实现动画
您已经注意到我们在修饰符中添加了动画效果keyboardAdaptive。这样可以确保键盘出现或消失时,边距调整也会随之动画显示,从而为用户提供流畅的体验。
4. 关闭键盘
在某些情况下,您可能希望用户通过点击外部TextField或“完成”按钮来关闭键盘。
- 敲击外部:
extension View {
func endEditing() {
UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
}
}
// Usage:
var body: some View {
VStack {
TextField("Enter text", text: $inputText)
}
.onTapGesture {
self.endEditing()
}
}
- 使用“完成”按钮:
var body: some View {
VStack {
TextField("Enter text", text: $inputText)
Button("Done") {
self.endEditing()
}
}
}
5. 键盘自定义
SwiftUI 允许您通过调整TextField修饰符来自定义键盘的外观和行为。
TextField("Enter email", text: $email)
.keyboardType(.emailAddress) // Sets the keyboard type
.autocapitalization(.none) // Disables auto-capitalization
.disableAutocorrection(true) // Disables auto-correction
结论:在 SwiftUI 中有效地管理键盘,可以确保用户在与应用交互时获得流畅直观的体验。通过监听键盘通知、为视图调整添加动画效果,以及集成一些便捷的扩展,您可以创建一个能够无缝适应键盘事件的精美用户界面。
想要了解更多开发方面的文章,请查看 Dopebase编程教程。
希望这篇教程能为你使用 SwiftUI 管理键盘打下坚实的基础。祝你编码愉快!
文章来源:https://dev.to/mrcflorian/managing-the-keyboard-in-swiftui-a-compressive-tutorial-11p0