Categories
Uncategorized

How to limit the number of characters in a SwiftUI TextField

Did you ever ask yourself how to limit the number of characters that are allowed to enter into a SwiftUI TextField? To set the maximum length for a text field, follow these steps 👇


Step 1: First of all, create a new Swift file and make sure you import the SwiftUI framework (and the AudioToolbox framework for letting the device vibrate later on).

import SwiftUI
import AudioToolbox


Step 2: Inside this file, you need to create an @ObservableObject that serves as the TextField’s manager und updates the related ContentView whenever the TextField will get updated. 

import SwiftUI
import AudioToolbox

class TextFieldManager: ObservableObject {
  
    
}


Step 3: Within the the TextfieldManager, we create a constant for setting the maximum length for our TextField.

class TextFieldManager: ObservableObject {
    
    let characterLimit = 4
    
}


Step 4: Next, make sure to create a @Published property for holding the TextField’s input and for updating the related ContentView whenever the input changes.

class TextFieldManager: ObservableObject {
    
    let characterLimit = 4
    
    @Published var userInput = ""
    
}


Step 5: In your ContentView, create a TextFieldManager instance and observe it by using the @ObservedObject property wrapper.

struct ContentView: View {

    @ObservedObject var textFieldManager = TextFieldManager()

    var body: some View {
        //...
    }
}


Step 6: Now we can create our actual TextField and bind it to the @Published property of our TextFieldManager instance

var body: some View {
        TextField("Enter something...", text: $textFieldManager.userInput)
            .padding()
            .background(Color(red: 239.0/255.0, green: 243.0/255.0, blue: 244.0/255.0, opacity: 1.0))
            .cornerRadius(5.0)
            .padding()
    }


Step 7: Back to our TextFieldManager.swift file: We must react every time the TextField gets updated. We do this by using the didSet property observer. 

@Published var userInput = "" {
        didSet {
            
        }
    }


Step 8: So every time the user enters a character we want to check if the userInput already exceeds the character limit. If that’s the case, we crop the new value to the allowed number of characters.

@Published var userInput = "" {
        didSet {
            if userInput.count > characterLimit {
                userInput = String(userInput.prefix(characterLimit))
            }
        }
    }


Step 9: Optionally, you can let the device vibrate when the allowed number gets exceeded by using the following method.

didSet {
            if userInput.count > characterLimit {
                userInput = String(userInput.prefix(characterLimit))
                AudioServicesPlayAlertSoundWithCompletion(SystemSoundID(kSystemSoundID_Vibrate)) { return }
            }
        }


And that’s it. This is how you limit the number of characters in a SwiftUI TextField! ✨

I hope you enjoyed this tutorial! If you want to learn more about SwiftUI, check out our other tutorials! Also make sure you follow us on Instagram and subscribe to our newsletter to not miss any updates, tutorials and tips about SwiftUI and more!