Controlling accessibility voice over readout of numbers in iOS - ios

I'm trying to get an accessibilityValue with a decimal number on a custom UIView to readout as "twenty point one", for example, similar to how voice over reads out the duration and keyframe values on the video trimmer when editing a video in the Photos app.
The default setup reads out the value as "twenty dot one". If I set the accessibilityAttributedLabel instead using the accessibilitySpeechPunctuation key, it reads as "twenty period one".
view.accessibilityAttributedLabel = NSAttributedString(string: "20.1", attributes: [.accessibilitySpeechPunctuation: true])
Without resorting to manually building a numeric string to read out, anyone know how to get the number to read saying "point" instead of "dot" or "period"?

Got it! Formatting a number using a NumberFormatter with a style of .spellOut will generate a string with the fully spelled out value. Not what we want for a label's text, but exactly what we want for an accessibility label.
let formatter = NumberFormatter()
formatter.numberStyle = .spellOut
let label = UILabel()
label.text = formatter.string(from: 20.1)
label.accessibilityLabel = formatter.string(from: 20.1)
// prints out "twenty point one"
print(label.accessibilityLabel)

Related

NumberFormatter negative value to positive

I would like to convert a negative value into a positive one using NumberFormatter. The value should represent a percent change and should look like this: 1.46% even if the value is negative -1.46.
There is a numberFormatter.negativeFormat, but I am unsure what the format should look like. I tried numberFormatter.negativeFormat = "0.00" but the percent sign disappears and I do not want to add it explicitly at the end, because I am using numberStyle
numberFormatter.numberStyle = .percent
Any ideas what would be the best solution?
You can extend the Double type to create a specific property that returns a String with the absolute value:
extension Double {
var positivePercent: String {
return abs(self).formatted(.percent)
}
}
Usage:
let a = -0.0146
print(a.positivePercent) // 1.46%

Adding commas in to extended numbers in Swift

I'm wanting to add commas in to break up numbers within my iOS application.
For example:
Change 1000 into 1,000
Change 10,000 into 10,000
Change 100000 into 100,000
And so on...
What is the most efficient way of doing this, and safe-guarding against numbers post decimal point too?
So for example,
1000.50 should return 1,000.50
My numbers at the moment are Ints, Doubles and Floats - so not sure if I need to manipulate them before or after converting to Strings.
Any feedback would be appreciated.
The Foundation framework (which is shared between iOS and MacOS) includes the NumberFormatter class, which will do exactly what you want. You'd configure a number formatter to include a groupingSeparator. (Note that different countries use different grouping separators, so you might want to set the localizesFormat flag to allow the NumberFormatter to change the separator character based on the user's locale.
Here is some sample code that will generate strings with comma thousands separators and 2 decimal places:
let formatter = NumberFormatter()
// Set up the NumberFormatter to use a thousands separator
formatter.usesGroupingSeparator = true
formatter.groupingSize = 3
//Set it up to always display 2 decimal places.
formatter.alwaysShowsDecimalSeparator = true
formatter.minimumFractionDigits = 2
formatter.maximumFractionDigits = 2
// Now generate 10 formatted random numbers
for _ in 1...10 {
// Randomly pick the number of digits
let digits = Double(Int.random(in:1...9))
// Generate a value from 0 to that number of digits
let x = Double.random(in: 1...(pow(10, digits)))
// If the number formatter is able to output a string, log it to the console.
if let string = formatter.string(from:NSNumber(value:x)){
print(string)
}
}
Some sample output from that code:
356,295,901.77
34,727,299.01
395.08
37,185.02
87,055.35
356,112.91
886,165.06
98,334,087.81
3,978,837.62
3,178,568.97

Swift NumberFormatter formatting all values to 3 decimal places?

I have a large array of doubles, which have a varying number of decimal places, such as:
[11307.3, 1025.64, 1.27826, 1676.46, 0.584175, 183.792, 1.02237, 13.649, 0.472665, 127.604]
I am attempting to format the number so there are commas every thousand and the decimal places are not formatted to a specific number such as 3dp. The array should look like
[11,307.3, 1,025.64, 1.27826, 1,676.46, 0.584175, 183.792, 1.02237, 13.649, 0.472665, 127.604]
I have tried doing this by defining NumberFormatter as such:
let numberFormatter = NumberFormatter()
and then choosing decimal for style:
numberFormatter.numberStyle = NumberFormatter.Style.decimal
The values in the array are display in a table view, and when a user taps on for example the 2nd cell, in a new screen the value 1,025.64 would be displayed.
I used this code to do that:
var formattedPrice = numberFormatter.string(from: NSNumber(value:coinPriceDouble!))
self.coinPriceLbl.text = "\(coinTitleText!): \(Cryptocoin.instance.fiatSymbol)\(formattedPrice!)"
This works perfect for any value that does not have more than 3 decimal places.
If the user chose the 3rd value in the array, it would display 1.278 not 1.27826.
Is there any way to format these values with commas but not force them to a specific number of decimal places?
As vadian said, NumberFormatter is highly customisable.
Just play around its properties, like (you need to customise based on your needs):
let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = .decimal
numberFormatter.maximumFractionDigits = 3
Here the explanation for NumberFormatter's maximumFractionDigits property and related.
Here instead a blog that explains all the related aspects of NumberFormatter A Guide to NSNumberFormatter.
EDIT
Put the following code in a Playground and observe the result:
let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = .decimal
numberFormatter.maximumFractionDigits = 3
let formattedNumbers = [11307.3, 1025.64, 1.27826, 1676.46, 0.584175, 183.792, 1.02237, 13.649, 0.472665, 127.604].flatMap { number in
return numberFormatter.string(from: number)
}
print(formattedNumbers)
Link: https://stackoverflow.com/a/27571946/6655075 .
This solved my problem. As I had 3 values displaying, each from a different array, I would end up formatting all 3 whereas I only wanted to format 1 array.
extension Double {
static let twoFractionDigits: NumberFormatter = {
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.minimumFractionDigits = 2
formatter.maximumFractionDigits = 2
return formatter
}()
var formatted: String {
return Double.twoFractionDigits.string(for: self) ?? ""
}
}
I removed
var formattedPrice = numberFormatter.string(from: NSNumber(value:coinPriceDouble!))
And simply used
self.coinPriceLbl.text = "\(coinTitleText!): \(Cryptocoin.instance.fiatSymbol)\(coinPriceDouble!.formatted)"
Edit: As Dávid Pásztor mentioned, I only want to add the comma separator to the values which need it while still maintaining the precision of each value down to the last decimal value.
You could try setting the maximum fraction digits to a largish number.
numberFormatter.maximumFractionDigits = 15

Formatting a date to be fixed-width without zero-padding

I have a UITableView, in which each row displays a date and time plus a message (screenshot below). I'm using a single attributed string to display the text in the row (which is necessary for the color difference).
Because I don't want to zero-pad the month, day, or hour, the date on the left-hand side of the colon is variable length, which causes the list of messages to look disorganized.
The result I want is for all the colons to line up vertically, so that the messages line up, despite the number of characters in the date being variable. What's the best way to accomplish this?
I've tried essentially space-padding (by detecting the length of the month, day, and hour), but the result still doesn't line up perfectly and can result in long (ugly looking) blocks of whitespace when all three (month, date, and hour) need to be padded. Perhaps there is a way to distribute this extra space amongst all the characters evenly?
Date formatting:
//choose format for the date
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "M/d h:mma: "
dateFormatter.amSymbol = "am"
dateFormatter.pmSymbol = "pm"
Entering into the view:
//first put in the date
let classHistoryCellText = NSMutableAttributedString.init(string: formattedDate)
classHistoryCellText.addAttribute(NSForegroundColorAttributeName, value: UIColor.init(hex: "#00000", alpha: 0.3), range: NSMakeRange(0, lengthOfDate))
//append what the message is
classHistoryCellText.append(NSMutableAttributedString.init(string: classBeingViewed.classHistory[indexPath.row]["event"] as! String))
classHistoryCellText.addAttribute(NSForegroundColorAttributeName, value: UIColor.init(hex: "#00000"), range: NSMakeRange(lengthOfDate, classHistoryCellText.length - lengthOfDate))
//bold the entire thing and make it size fontSize
classHistoryCellText.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: fontSize), range: NSMakeRange(0, classHistoryCellText.length))
classHistoryCellToDisplay.textLabel?.attributedText = classHistoryCellText
Result:
Try changing your date formatter to:
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM/dd hh:mma: " // this line is changed
dateFormatter.amSymbol = "am"
dateFormatter.pmSymbol = "pm"
It will make months, days and hours to always have two digits which will make all your dates the same width.
This will work unless you have a specific requirement to avoid displaying leading zeros. If this is the case, the easiest solution is to use two labels - one for date and one for status. Make date label a fixed width.

Use MeasurementFormatter to display meters as feet

I'm having trouble getting the new MeasurementFormatter class to give me results in appropriate units. I have values in meters that I want to display in localized strings, either meters or feet depending on the user's locale.
I have this:
let meters : Double = 10
let metersMeasurement = Measurement(value: meters, unit: UnitLength.meters)
let measurementFormatter = MeasurementFormatter()
measurementFormatter.locale = Locale(identifier: "en_US")
let localizedString = measurementFormatter.string(from: metersMeasurement)
This gives me a string of "0.006mi". It's correct, I guess, but converting 10 meters to miles is kind of ridiculous. What I want is "32.8ft".
The .providedUnit option on MeasurementFormatter isn't helpful-- that just gives me a result in meters.
I could look up the current locale and handle this myself, but that's exactly the kind of thing that MeasurementFormatter is supposed to make unnecessary. Is there some way to get it to do what I need?
You should set the formatter's unitOptions to naturalScale:
let measurementFormatter = MeasurementFormatter()
measurementFormatter.unitOptions = .naturalScale
And you should only set the locale if you want every user in any locale to see the value in the specific locale.

Resources