Loading...

How to add a character limit to a TextField in SwiftUI?

question swiftui swift
Ram Patra Published on September 13, 2024

To add a character length limit to a TextField in SwiftUI, you can use a combination of Swift’s .onChange, .onPasteCommand modifier, and string manipulation to limit the number of characters the user can enter.

The .onPasteCommand modifier in SwiftUI allows you to handle content pasted into a TextField directly. You can use this modifier to intercept and manage the pasted content before it actually gets added to the TextField. This way, you can enforce the character limit when the user pastes text.

Here’s how to use .onChange and .onPasteCommand to limit the pasted text:

import SwiftUI

struct ContentView: View {
    @State private var text: String = ""
    let characterLimit = 20 // Set your desired character limit
    
    var body: some View {
        VStack {
            TextField("Insert text here...", text: $text)
                .padding()
                .background(Color.white)
                .cornerRadius(10)
                .shadow(radius: 3)
                .padding(.horizontal)
                .onChange(of: text) { newValue in
                    // Enforce character limit while typing
                    if newValue.count > characterLimit {
                        text = String(newValue.prefix(characterLimit))
                    }
                }
                .onPasteCommand(of: [.plainText]) { items in
                    // Handle paste event and enforce character limit
                    if let pastedText = items.first?.string {
                        let newText = text + pastedText
                        if newText.count > characterLimit {
                            // Limit the pasted content to fit within the character limit
                            text = String(newText.prefix(characterLimit))
                        } else {
                            text = newText
                        }
                    }
                }
            
            Text("\(text.count)/\(characterLimit) characters") // Optional: Shows character count
                .font(.footnote)
                .foregroundColor(text.count > characterLimit ? .red : .gray)
                .padding(.top, 5)
        }
        .padding()
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

Explanation:

  1. .onPasteCommand(of: [.plainText]):
    • This modifier intercepts the paste command. It ensures that only plain text is handled when pasting into the TextField.
    • Inside this block, you can access the pasted content and modify it before it’s added to the TextField.
  2. Handle the pasted content:
    • When the user pastes text, it gets appended to the current value of text.
    • The pasted content is checked against the character limit, and if the combined length (existing + pasted) exceeds the limit, the text is truncated to fit within the limit.
  3. Fallback to onChange for typing:
    • The onChange modifier still ensures the limit is enforced while typing.

This approach ensures that you can handle pasting specifically while still enforcing the character limit. The user won’t be able to exceed the specified character limit when pasting long text nor when typing.

Take your presentation to the next level.

Put your face and name on your screen.

Your to-dos on your menu bar.

Fill forms using your right-click menu.

Ram Patra Published on September 13, 2024
Image placeholder

Keep reading

If this article was helpful, others might be too

question swiftui March 6, 2023 How to render the icon on a menu bar as a template in SwiftUI?

Setting your app’s icon on the menu bar as a template makes it to adapt to light and dark modes automatically without you doing anything. To do this, you have to use this constructor of MenuBarExtra class.

question swiftui swift February 19, 2025 How to change the window level to floating, popUpMenu, etc. in SwiftUI?

When developing macOS applications with SwiftUI, you might need to create floating windows that stay on top of other windows. While modern macOS versions (15+) make this straightforward with the .windowLevel(.floating) modifier, supporting older versions requires a different approach. In this post, I’ll show you how to create floating windows that work across different macOS versions.

question swiftui swift September 8, 2024 How to loop through an enum in SwiftUI?

In SwiftUI, looping through an enum is not directly possible without some extra work because enums in Swift don’t inherently support iteration. However, you can achieve this by making the enum CaseIterable, which automatically provides a collection of all cases in the enum.

Like my work?

Please, feel free to reach out. I would be more than happy to chat.