Oliver
Oliver

Reputation: 181

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))
}

Upvotes: 10

Views: 8937

Answers (3)

rony_y
rony_y

Reputation: 605

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.

Upvotes: 12

lmunck
lmunck

Reputation: 665

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)}))

Upvotes: 2

Cenk Bilgen
Cenk Bilgen

Reputation: 1435

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.

Upvotes: 30

Related Questions