SwiftUI: TextField max limit

Ronak Patel
Aug 3, 2022

TextField is a control that displays an editable text interface.

In this blog, we’ll learn how to set the maximum limit of a text in Textfield using Combine.

The most elegant (and simple) way to set a character limit on the TextField is to use the native publisher event collect().

collect()Collects all received elements, and emits a single array of the collection when the upstream publisher finishes.

import SwiftUI
import Combine
struct ContentView: View {
@State var text = ""
var body: some View {
TextField("Set the max length", text: $text)
.font(Font.system(size: 16))
let result = String($0.prefix(240))
if text != result {
text = result
Text("\(text.count)/240 Characters")

Reference taken from,