0

I am having one textfield and I am using it to enter email and when a user clicks the send button, the email is deleted from the same textfield and its placeholder changes to enter pin. So when the user enters pin, I would like to make the text field to be limited up to 6 characters. Is this possible? If yes, please help me I am new to SwiftUI.

TextField(placeholder, text: $text)

The $text changes according to the states email or pin

Asperi
  • 228,894
  • 20
  • 464
  • 690
user12723399
  • 127
  • 1
  • 1
  • 5

1 Answers1

3

You can do it using Publisher and onReceive.

import SwiftUI

struct ContentView: View {
    @State var text:String = ""
    var body: some View {
        VStack{
            TextField("Enter text", text: $text)
                .onReceive(text.publisher.last()) { (output) in
                    if self.text.count>6{ //set count as you want
                        self.text = String(self.text.dropLast())
                    }
            }
        }
    }
}
Rohit Makwana
  • 4,337
  • 1
  • 21
  • 29