在更改文本字段的禁用状态时获取' AttributeGraph: cycle detected '错误



当我在我的视图中更新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
}
}
}
}

相关内容

  • 没有找到相关文章

最新更新