更改文本字段的禁用状态时出现“AttributeGraph:检测到循环”错误

wri*_*nds 8 debugging xcode swiftui swiftui-texteditor

当我更新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 }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

我该如何修复这个错误?

wri*_*nds 29

经过几个小时的痛苦调试,我找到了解决方案!

事实证明,问题在于当用户仍在编辑文本字段时,您无法禁用该文本字段。相反,您必须首先退出文本字段(即关闭键盘),然后禁用文本字段。

这是我更新的代码:

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
    )
  }
}
Run Code Online (Sandbox Code Playgroud)