DEV Community

Troy Husted
Troy Husted

Posted on

Tutorial: SwiftUI Character Limit in a TextField

Here is a simple, but handy tutorial for limiting the number of characters in a TextField. I use this in my app Recitation to limit the number of characters that the user can have for different tags.

Validated for Swift Version 5.9

Step 1: Combine & Just()

import Combine
Enter fullscreen mode Exit fullscreen mode

Per Apple's documentation, the Combine framework "provides a declarative Swift API for processing values over time. These values can represent many kinds of asynchronous events. Combine declares publishers to expose values that can change over time, and subscribers to receive those values from the publishers." It's use for us today is the Just() function, which is a publisher used to return a result a singular time.

Step 2: Limit Text Function

func limitText(_ limit: Int) {
    if subTaskText.count > limit {
        subTaskText = String(subTaskText.prefix(limit))
    }
}
Enter fullscreen mode Exit fullscreen mode

This function uses the parameter limit to determine if subTaskText (the string holding the user's typed text) is greater than the imposed character limit. If the user attempts to type additional characters beyond the limit, the subTaskText will be truncated to the limit.

Step 3: Implementation

VStack {
    TextField("The next thing to do...", text: $subTaskText)
        .font(.custom("Quicksand", size: 20))
        .focused($isFocused)
        .onReceive(Just(subTaskText)) { _ in limitText(textLimit) }
}

Enter fullscreen mode Exit fullscreen mode

To implement the character limit function, we simply add the .OnReceive modifier to the TextField.

Top comments (0)