UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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

1      

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
    }
}

5      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

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

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

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.