Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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))
}
like image 464
Oliver Avatar asked Jan 20 '20 14:01

Oliver


3 Answers

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.

like image 120
Cenk Bilgen Avatar answered Sep 17 '22 10:09

Cenk Bilgen


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.

like image 32
rony_y Avatar answered Sep 21 '22 10:09

rony_y


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)}))
like image 36
lmunck Avatar answered Sep 17 '22 10:09

lmunck