The Finnternet Like the Internet but with more me

Get Swifty: Currency Textfield

When working on one of my recent projects I ran into the case where I had a textfield that represented a currency. Naturally, you want a currency symbol to prepend the text input, easy right? Wrong! Well maybe it’s not that hard (and there are libraries you can use that will do it for you), but it is harder than you would think. The user should be able to delete the numbers they inputted but not the symbol, the symbol needs to be stripped off when evaluating the input as a number, & the symbol has to be matched to their country.

Currency Textfield

I found this gem while watching some instructional videos & thought it was a great solution to this problem. The code in the following draw function creates a UILabel, sets it just inside the left side of the text field, does some visual stuff, & then uses a formatter to add the correct currency symbol.

override func draw(_ rect: CGRect) {
    let size: CGFloat = 20
    let currencyLabel = UILabel(frame: CGRect(x: 5, y: (frame.size.height / 2) - (size / 2), width: size, height: size))
    currencyLabel.backgroundColor = #colorLiteral(red: 0.8809662074, green: 0.8809662074, blue: 0.8809662074, alpha: 0.7980789812)
    currencyLabel.textAlignment = .center
    currencyLabel.textColor = #colorLiteral(red: 0.2549019754, green: 0.2745098174, blue: 0.3019607961, alpha: 1)
    currencyLabel.layer.cornerRadius = 5.0
    currencyLabel.clipsToBounds = true
    let formatter = NumberFormatter()
    formatter.numberStyle = .currency
    formatter.locale = .current
    currencyLabel.text = formatter.currencySymbol