swiftuitextfieldswift5maxlengthcharacter-limit

Is it possible to set a character limit on a TextField using SwiftUI?


[RESOLVED]

I am using a codable struct which stores the object values retrieved from an API call so I have amended my TextField using Cenk Belgin's example, I've also removed extra bits I've added in so if anyone else is trying to do the same thing then they won't have pieces of code from my app that aren't required.

TextField("Product Code", text: $item.ProdCode)

    .onReceive(item.ProdCode.publisher.collect()) {

    self.item.ProdCode = String($0.prefix(5))
}

Solution

  • Here is one way, not sure if it was mentioned in the other examples you gave:

    @State var text = ""
    
      var body: some View {
        TextField("text", text: $text)
          .onReceive(text.publisher.collect()) {
            self.text = String($0.prefix(5))
        }
      }
    

    The text.publisher will publish each character as it is typed. Collect them into an array and then just take the prefix.