我想在 SwiftUI 中关闭
TextField
的预测文本/自动更正。看起来这在 UITextField
中是可能的:
禁用 UITextField 预测文本
我检查了Apple文档中的
TextField
并用谷歌搜索,但找不到任何关于此的信息。
有人找到了禁用文本字段的预测文本/自动完成的方法吗?
谢谢!
似乎现在可以使用 Xcode 11 Beta 5。有一个新的修改器可以禁用 TextField 上的自动更正
func disableAutocorrection(_ disable: Bool?) -> some View
编辑: 修饰符 disableAuto Correction 在 iOS 16.1 中已弃用。新的修饰符是 auto CorrectionDisabled:
func autocorrectionDisabled(_ disable: Bool = true) -> some View
这应该有效:
.disableAutocorrection(true)
对于 iOS 16.2 SDK,我需要这样做:
.keyboardType(.alphabet)
.textContentType(.oneTimeCode)
.autocorrectionDisabled(true)
(
oneTimePasscode
是一个旧的UIKit hack,可以达到相同的结果。这对我来说感觉很脏,如果这种行为将来再次发生变化,我不会感到惊讶......)
事实证明,您需要将键盘类型设置为
.alphabet
才能使 .disableAutocorrection(true)
正常工作。
这是我使用的扩展:
extension View {
func removePredictiveSuggestions() -> some View {
self.keyboardType(.alphabet)
.disableAutocorrection(true)
}
}
Xcode 12.3 斯威夫特 5.3
如果您需要在多个
TextField
上禁用自动更正,或者确实添加其他修饰符,则创建一个自定义 TextField:
struct TextFieldCustom: View {
let title: String
let text: Binding<String>
init(_ title: String, text: Binding<String>) {
self.title = title
self.text = text
}
var body: some View {
TextField(title, text: text)
.disableAutocorrection(true)
// add any other modifiers that you want
}
}
用法示例:
Form {
Section(header: Text("Details")) {
TextFieldCustom("Field1", text: $field1)
TextFieldCustom("Feild2", text: $field2)
TextFieldCustom("Field3", text: $field3)
}
}
.keyboardType(.asciiCapable)
.autocorrectionDisabled(true)
.alphabet
已弃用并已被 .asciiCapable
取代。