9

[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))
}
Oliver
  • 161
  • 2
  • 9

3 Answers3

29

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.

Cenk Bilgen
  • 1,330
  • 9
  • 8
12

From iOS 14 you can add onChange modifier to the TextField and use it like so :

TextField("Some Placeholder", text: self.$someValue)
    .onChange(of: self.someValue, perform: { value in
       if value.count > 10 {
           self.someValue = String(value.prefix(10))
      }
  })

Works fine for me.

rony_y
  • 535
  • 1
  • 8
  • 26
2

You can also do it in the Textfield binding directly:

TextField("Text", text: Binding(get: {item.ProCode}, set: {item.ProCode = $0.prefix(5).trimmingCharacters(in: .whitespacesAndNewlines)}))
lmunck
  • 505
  • 4
  • 12