WWDC22 SALE: Save 50% on all my Swift books and bundles! >>

SOLVED: Limit # characters in a Textfield

Forums > SwiftUI

I want to be ablo to limit the number of characters entered in a Textfield. I've found some solutions using Combine and that works partially (this also only allows numeric characters):

TextField("Year", text: $year)
    .keyboardType(.decimalPad)
    //limit to numbers only (on all platforms) and limit to 4 chars
    .onReceive(Just(year)) { newValue in
        let filtered = newValue.filter { Set("0123456789").contains($0) }
        if filtered != newValue {
            self.year = filtered
        }
    }
    .onReceive(Just(year)) { _ in
        if year.count > 4 {
            year = String(year.prefix(4))
        }
    }

When pasting a large text it caps it neatly at 4 characters. But when. using the keyboard/pad both hardware and soft, I am able to enter more than 4!

Any tips?

EDIT: Hmmmm, on a real device it seems to work!

Would be interested in a more generic approach

   

This solution works kike a charm on all Texfields:

extension Binding where Value == String {
    func max(_ limit: Int) -> Self {
        if self.wrappedValue.count > limit {
            DispatchQueue.main.async {
                self.wrappedValue = String(self.wrappedValue.dropLast())
            }
        }
        return self
    }
}

   

Hacking with Swift is sponsored by RevenueCat

SPONSORED You know StoreKit, but you don’t want to do StoreKit. RevenueCat makes it easy to deploy, manage, and analyze in-app subscriptions on iOS and Android so you can focus on building your app.

Explore the docs

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.