当我在我的视图中更新isDisabled
状态变量时,它按预期更新了我的文本字段的.disabled
修饰符,但它随后导致大约40个以下错误的实例出现在控制台中(最后有不同的属性号):=== AttributeGraph: cycle detected through attribute 200472 ===
然后写着:AttributeGraphError[59460:4808136] [SwiftUI] Modifying state during view update, this will cause undefined behavior.
struct ContentView: View {
@State var isDisabled = false
@State var text = ""
var body: some View {
VStack {
TextField("", text: $text)
.textFieldStyle(.roundedBorder)
.disabled(isDisabled)
Button("Disable text field") { isDisabled = true }
}
}
}
如何修复此错误?
经过几个小时的痛苦调试,我找到了解决方案!
原来的问题是,你不能禁用文本字段,而用户仍在编辑字段。相反,你必须首先退出文本字段(即关闭键盘),然后禁用文本字段。
这是我更新的代码:
struct ContentView: View {
@State var isDisabled = false
@State var text = ""
var body: some View {
VStack {
TextField("", text: $text)
.textFieldStyle(.roundedBorder)
.disabled(isDisabled)
Button("Disable text field") {
closeKeyboard()
isDisabled = true
}
}
}
func closeKeyboard() {
UIApplication.shared.sendAction(
#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil
)
}
}
这是一个iOS 15+解决方案。
struct ContentView: View {
enum Field: Hashable {
case text
}
@FocusState private var focusedField: Field? // available iOS 15+
@State var isDisabled = false
@State var text = ""
var body: some View {
VStack {
TextField("", text: $text)
.focused($focusedField, equals: .text)
.textFieldStyle(.roundedBorder)
.disabled(isDisabled)
Button("Disable text field") {
focusedField = nil
isDisabled = true
}
}
}
}