I'm trying to represent running pace in my app - let's say 5min/km.
For voice over, I'd love this to be read as five minutes per kilometer.
I know I can get kilometers like that:
let measurementFormatter = MeasurementFormatter()
measurementFormatter.unitStyle = .long
measurementFormatter.string(from: UnitLength.kilometers)
but would it be possible to get the singular form (and take advantage of the already localized units)?
CodePudding user response:
It looks like the only native way to do this would be create an explicit measurement and manually remove the singular unit ("1"):
let measurementFormatter = MeasurementFormatter()
measurementFormatter.unitStyle = .long
measurementFormatter.unitOptions = .providedUnit
let length: Measurement<UnitLength> = .init(value: 1, unit: .kilometers)
let str = measurementFormatter.string(from: length)
.replacingOccurrences(of: "1", with: "")
.replacingOccurrences(of: " ", with: " ")
.trimmingCharacters(in: .whitespaces)
I'm no language expert but I expect this will work with most (if not all) languages.
CodePudding user response:
Edit
It looks like it's possible to create a custom MeasurementFormatter that outputs in minutes/km or minutes/mile. See the tutorial at https://www.raywenderlich.com/553-how-to-make-an-app-like-runkeeper-part-1 for an example of how to do this.