SwiftUI: TextField max limit

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,



iOS Developer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store