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
  • 173,274
  • 14
  • 284
  • 455
user12723399
  • 67
  • 1
  • 1
  • 4

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
  • 3,668
  • 1
  • 19
  • 27