Home > other >  OnSubmit - Update view when variable changes
OnSubmit - Update view when variable changes

Time:11-26

I have a textfield that gives the user a limit of 150 characters. If the user exceeds the amount, the text block will display when they submit the update.

The text block under the field will display and updates the number variable depending on how many characters they exceeded (ie. "Shorten text by 3 characters, shorten text by 2 characters..etc)

enter image description here

I would love if I can have the text block disappear once the user deletes characters and we hit the character limit. (once the number hits 0 in the gif above, the block would disapear)

function called to determine if total characters exceeds limit

func bioCharacterExceededBy() -> String{
   var charRemaining = charLimit - userBio.count
    if charRemaining == charLimit{
        isUserBioValid = true
    }
    return String(charRemaining)
}

Textfield

 TextField(bio ?? "Name unavailable", text: $userBio).submitLabel(.done)
                .onSubmit{
                    if(userBio.count < charLimit){
                        isUserBioValid = true
                        if (vm.userModel?.userBio != userBio){
                            //recipe saved
                        }
                    }
                    else {
                       isUserBioValid = false
                    }
                  
                }

Text that triggers under Textfield

Text(!isUserBioValid ? "Please shorten Bio by \(bioCharacterExceededBy()) characters" : "")
            .foregroundColor(.red)
            .font(.caption)
            .listRowSeparator(.hidden)

CodePudding user response:

You are overthinking this, there is a more simple solution to this.

Instead of determining the validity on submission, test for it with an if clause. If it exceeds the limit show the Text else don´t. On submission you can fix the input if you like by prefixing the text var.

struct ContentView: View{
    
    @State private var text: String = ""
    private var maxCount: Int = 5
    
    var body: some View{
        VStack{
            TextField("", text: $text)
                .onSubmit {
                    text = String(text.prefix(maxCount))
                }
                .textFieldStyle(.roundedBorder)
            if text.count > maxCount{
                Text("you exceeded the max allowed characters by \(text.count - maxCount)")
                    .foregroundColor(.red)
                    .font(.caption)
            }
        }
    }
}
  • Related