使用“true”或“false”可以按预期工作:
TextEditor(text: $input)
.autocorrectionDisabled(true)
但是当替换为 State 变量时,仅使用初始值。当状态值更改为“false”时,自动更正的行为不会更改。
@State var shouldDisable = true
TextEditor(text: $input)
.autocorrectionDisabled(shouldDisable)
.onReceive(aTimer) { _ in
if otherConditionMet {
withAnimation {
shouldDisable = false
}
print(shouldDisable)
}
}
计时器每秒触发一次以评估是否满足其他条件。这是简单打印语句的输出,确认满足其他条件时应该禁用更新:
`shouldDisable: true`
`shouldDisable: true`
`shouldDisable: true`
`shouldDisable: true`
`shouldDisable: true
`shouldDisable: false`
`shouldDisable: false`
`shouldDisable: false`
我已经通过将
shouldDisable
初始化为 true
并再次初始化为 false
并在 if 语句中更新 shouldDisable = true
进行了验证。在这两种情况下,无论变量如何变化,都只使用初始值。
我尝试删除
withAnimation
,以及堆栈中 .autocorrectionDisabled
修饰符的顺序;都没有任何效果。
我正在使用 iOS 15 的物理设备上进行测试,因为这是我最早支持的目标。
感谢您的任何意见!
更新:我刚刚使用以下基本代码验证了此行为。布尔值切换为 false,但文本编辑器不会重新启用自动更正:
struct ContentView: View {
@State var input = ""
@State var autocorrectionDisabled = true
var body: some View {
VStack {
TextEditor(text: $input)
.autocorrectionDisabled(autocorrectionDisabled)
.font(.headline)
Button("Toggle Autocorrection") {
autocorrectionDisabled.toggle()
print("autocorrectionDisabled: \(autocorrectionDisabled)")
}
.padding()
}
.padding()
}
}
我很想听听其他人的结果和关于如何解决这个问题的想法。
如果您将
TextField
设置为 Bool
,您可以“重置”
id
TextEditor(text: $input)
.autocorrectionDisabled(autocorrectionDisabled)
.font(.headline)
.id(autocorrectionDisabled)
这会使
TextField
失去焦点,因此您必须使用 FocusState
进行补偿,或者保持原样并期望用户触发焦点。