Learning about iOS development?
I am the author of iOS 17 Fundamentals, Building iOS User Interfaces with SwiftUI, and eight other courses on Pluralsight.
Deepen your understanding by watching!
I am the author of iOS 17 Fundamentals, Building iOS User Interfaces with SwiftUI, and eight other courses on Pluralsight.
Deepen your understanding by watching!
Displaying and Updating Currency in a UILabel
Setup
1import UIKit
2import PlaygroundSupport
3
4class MyViewController : UIViewController {
5
6 var currencyLabel = UILabel()
7 override func loadView() {
8 let view = UIView()
9 view.backgroundColor = .white
10
11 currencyLabel.frame = CGRect(x: 150, y: 200, width: 200, height: 20)
12 currencyLabel.text = "$0.00"
13 currencyLabel.textColor = .black
14
15 view.addSubview(currencyLabel)
16 self.view = view
17 }
18}
19
20let viewController = MyViewController()
21PlaygroundPage.current.liveView = viewController
Live View
Exract the current currency value from the label
Chances are, you’re displaying whatever currency value you’re displaying as a String
in your user interface.
Therefore, you need to extract it out of whatever UI element you’re displaying it in, and get it ready to do “number stuff” with…
1let currentTotalString = viewController.currencyLabel.text?.replacingOccurrences(of: "$", with: "", options: String.CompareOptions.literal, range: nil)
2
3var currentTotal = NSDecimalNumber(string: currentTotalString)
0
Make a random currency amount to add to the current total
For this example, create a random number to between 0 and 5 to test out adding some amount to the current total.
1let randomRange = Range<Double>(uncheckedBounds: (0.0,5.0))
2let randomAmount = Double.random(in: randomRange)
3let amountToAdd = NSDecimalNumber(floatLiteral: randomAmount)
2.095023084295587 // Output from my Playground run
Add to the current total
1currentTotal = currentTotal.adding(amountToAdd)
2.095023084295587 // Output from my Playground run
Make a currency formatter, format as currency, and update the UI
The way to format numbers as currency is with a NumberFormatter. I’m keeping it simple in this example, but there are various customization points available to you.
1let currencyFormatter = NumberFormatter()
2currencyFormatter.locale = Locale.current
3currencyFormatter.usesGroupingSeparator = true
4currencyFormatter.numberStyle = NumberFormatter.Style.currency
5
6viewController.currencyLabel.text = currencyFormatter.string(from: currentTotal)
Live View
comments powered by Disqus