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

As - You - Type - String Formatting Textfield

Forums > SwiftUI

Searched high and low, and cannot figure out if this is possible. I have a Textfield where a user enters numbers in a string. I would like the Textfield to display in real time as currency. Instead of showing 25000, I'd like it to auto format to $25,000, but still be stored as just 25000 for it's @State. Just displaying inside the Textfield in real time as one is typing.

3      

I do not think that you can do this as it a Text input, Maybe show a "Label" above with the formatting done there. Will keep an eye on this question if anyone else has an answer.

3      

@randallgrimm
16h Searched high and low, and cannot figure out if this is possible. I have a Textfield where a user enters numbers in a string. I would like the Textfield to display in real time as currency. Instead of showing 25000, I'd like it to auto format to $25,000, but still be stored as just 25000 for it's @State. Just displaying inside the Textfield in real time as one is typing.

struct ContentView: View {
    @State
    private var input: String = ""
    var body: some View {
        VStack {
            TextField("placeholder", text: $input)
                .keyboardType(.numberPad)
                .textFieldStyle(RoundedBorderTextFieldStyle())
                .padding()
                .onChange(of: input) { value in
                   here handle the events ...
                }
        }
    }
}

3      

I had the same problem awhile back and eventually created my own solution. I'm sure there is a better one out there but this does the trick. Started with using the onChange method but quickly realized that it silos it over time and you need to change to currency on the fly without a text field. So, I created an extensionof String to format the text.

extension String {
    func currency() -> String {
        var string = self.replacingOccurrences(of: "$", with: "").replacingOccurrences(of: ",", with: "")
        var coin = ""
        if let range = string.range(of: ".") {
            let coins = string[range.upperBound...]
            coin = "."+coins
            string.removeSubrange(range.upperBound...)
            string = string.replacingOccurrences(of: ".", with: "")
            if coin.count > 3 {
                coin = String(coin.dropLast())
                string.append(coin)
                return string
            }
        }
        if string.count > 0 {
            switch string.count {
                case 4:
                    string.insert(",", at: string.index(string.startIndex, offsetBy: 1))
                case 5:
                    string.insert(",", at: string.index(string.startIndex, offsetBy: 2))
                case 6:
                    string.insert(",", at: string.index(string.startIndex, offsetBy: 3))
                case 7:
                    string.insert(",", at: string.index(string.startIndex, offsetBy: 1))
                    string.insert(",", at: string.index(string.startIndex, offsetBy: 5))
                case 8:
                    string.insert(",", at: string.index(string.startIndex, offsetBy: 2))
                    string.insert(",", at: string.index(string.startIndex, offsetBy: 6))
                case 9:
                    string.insert(",", at: string.index(string.startIndex, offsetBy: 3))
                    string.insert(",", at: string.index(string.startIndex, offsetBy: 7))
                case 10:
                    string.insert(",", at: string.index(string.startIndex, offsetBy: 1))
                    string.insert(",", at: string.index(string.startIndex, offsetBy: 5))
                    string.insert(",", at: string.index(string.startIndex, offsetBy: 9))
                case 11:
                    string.insert(",", at: string.index(string.startIndex, offsetBy: 2))
                    string.insert(",", at: string.index(string.startIndex, offsetBy: 6))
                    string.insert(",", at: string.index(string.startIndex, offsetBy: 10))
                case 12:
                    string.insert(",", at: string.index(string.startIndex, offsetBy: 3))
                    string.insert(",", at: string.index(string.startIndex, offsetBy: 7))
                    string.insert(",", at: string.index(string.startIndex, offsetBy: 11))
                case 13:
                    string.insert(",", at: string.index(string.startIndex, offsetBy: 1))
                    string.insert(",", at: string.index(string.startIndex, offsetBy: 5))
                    string.insert(",", at: string.index(string.startIndex, offsetBy: 9))
                    string.insert(",", at: string.index(string.startIndex, offsetBy: 13))
                case 14:
                    string.insert(",", at: string.index(string.startIndex, offsetBy: 2))
                    string.insert(",", at: string.index(string.startIndex, offsetBy: 6))
                    string.insert(",", at: string.index(string.startIndex, offsetBy: 10))
                    string.insert(",", at: string.index(string.startIndex, offsetBy: 14))
                case 15:
                    string.insert(",", at: string.index(string.startIndex, offsetBy: 3))
                    string.insert(",", at: string.index(string.startIndex, offsetBy: 7))
                    string.insert(",", at: string.index(string.startIndex, offsetBy: 11))
                    string.insert(",", at: string.index(string.startIndex, offsetBy: 15))
                default:
                    break
            }
            string.insert("$", at: string.startIndex)
        }
        string.append(coin)
        string = string.replacingOccurrences(of: " ", with: "")
        return string
    }
}

3      

You can also use below. Found it on swiftwithmajid.com. Pretty simple and straightforward for the textfield.

extension NumberFormatter {
    static var currency: NumberFormatter {
        let formatter = NumberFormatter()
        formatter.numberStyle = .currency
        return formatter
    }
}

struct ContentView: View {
    @State private var price = 99

    var body: some View {
        TextField(
            "type something...",
            value: $price,
            formatter: NumberFormatter.currency
        )
    }
}

4      

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.