2

当我更新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 }
    }
  }
}

如何修复此错误?

4

1 回答 1

7

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

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

这是我更新的代码:

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
    )
  }
}
于 2021-10-20T22:04:14.353 回答