SwiftUI is a declarative language. Some of these errors won't appear if you keep revising your code to read as declarations... This is what I want SwiftUI to do.
This line doesn't seem very Swifty.
.disabled(text.count >= 5)
As a fellow coder, I have to stop and think about what you're trying to accomplish. Indeed, this is where the error is introduced.
However, with a simple change shown below, you can eliminate the error, and improve readability at the same time.
// Don't modify state variables during view update.
// For: vjcina jr
// By: Obelix 24 Mar 2022
// Paste into Playgrounds
import SwiftUI
import PlaygroundSupport
struct FieldLengthView: View { // Please don't use ContentView
@State private var myInputField = "" // Also, please use more descriptive variable names.
// Use computed booleans to keep your code clean
private var whenMyInputFieldHasFiveCharacters: Bool {
myInputField.count > 4
}
var body: some View {
TextField("Type Here", text: $myInputField)
.disabled(whenMyInputFieldHasFiveCharacters) // DECLARE why you disable this field
}
}
PlaygroundPage.current.setLiveView(FieldLengthView() )
When SwiftUI is building your view it grabs the external value of text
(confusing name, btw!). Then it needs to determine if the TextField
should be disabled or not; so it counts the number of characters. THEN it needs to push some characters into the TextField
to display in the view. However the variable text
is a wrapped value and internally has a current value and potentially another, newer value.
At this point, the view builder may find out that the new value is different from the value it used when determining if the field should be disabled or not. See? You are potentially changing the value, while the view is being constructed. Don't do this.