I have a user sign-up form that changes the color of the requested user name when its availability is checked. The color is based on an @State enum in the view:
struct SignUpView: View
{
enum ValueState
{
case unchecked
case good
case noGood
}
...
@State private var usernameCheck: ValueState = .unchecked
I build the bulk of the UI in a ViewBuilder function, so the body only contains this:
var body: some View
{
Group
{
ScrollView
{
signUpForm()
Text("This is some BS.")
.foregroundColor(usernameCheck == .unchecked ? .yellow :
usernameCheck == .good ? .green : .red)
}
}
}
As you can see, that text field’s color depends on that state variable. It works fine. If I put the exact same dependency on a text field added by a ViewBuilder, it doesn’t work.
@ViewBuilder func signUpForm() -> some View
{
VStack
{
Text("Sign up!")
.font(AppStyle.titleFont)
.padding(.bottom)
Group
{
Text("Desired username:")
.font(AppStyle.labelFont)
.frame(maxWidth: .infinity, alignment: .leading)
.padding(1)
HStack
{
TextField("", text: $tempUser.username)
.onChange(of: tempUser.username, perform: { value in
usernameChanged(toString: value) })
.foregroundColor(usernameCheck == .unchecked ? .yellow :
usernameCheck == .good ? .green : .red) <- DOES NOT WORK
I even tried passing userNameCheck
into the ViewBuilder. No dice. So how are ViewBuilders supposed to work?
1