Learn Courses My Dashboard

Limit number of characters in a TextField

I am using the latest version of Xcode and am using SwiftUI.

My question is how to limit the number of characters a user can enter in a TextField.
When I search for answers to this online I find answers but they don’t appear to work with the latest version of SwiftUI. They appear to remove extra characters from the TextField variable, but the TextField itself is not updated to show the removal of extra characters.

Hope this can be done. Help would be appreciated.

Thank you - Ed Campbell

Here is a very simple bit of code that limits your text input to a specific number of characters.

struct ContentView: View {
    @State private var inputText = ""
    @State private var characterLimit = 15

    var body: some View {
        VStack(spacing: 30) {
            TextField("Enter your text", text: $inputText)
            Text("Character count: \(inputText.count)")
        .onChange(of: inputText, perform: { _ in
            //  Every time a character is typed, onChange is triggered and the last character is removed from the
            if inputText.count > characterLimit {
                let limitedText = inputText.dropLast()
                inputText = String(limitedText)

Disclaimer: I have not downloaded Xcode 13 yet just because I am just lazy, so I can’t guarantee that this will work (Still using Xcode 12.5.1). That said, I have no reason to believe that it wont work.

You don’t even need to check the length first, just chop at the characterLimit regardless.

.onChange(of: inputText) { _ in
    inputText = String(inputText.prefix(characterLimit))

And just for the heck of it, I whipped this up to make it look nicer:

extension View {
    func limitText(_ text: Binding<String>, to characterLimit: Int) -> some View {
            .onChange(of: text.wrappedValue) { _ in
                text.wrappedValue = String(text.wrappedValue.prefix(characterLimit))

To be used like so:

TextField("TextField", text: $txt)
    .limitText($txt, to: 5)