Last active
November 13, 2022 10:00
-
-
Save lahariganti/14f310916cf267353d52ea3c1ab0406e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
import UIKit | |
extension Double { | |
func formatElevation() -> (AttributedString, AttributedString) { | |
let measurement = Measurement(value: self, unit: Locale.current.usesMetricSystem ? UnitLength.meters : UnitLength.feet) | |
var resultString = measurement.formatted(.measurement(width: .narrow, usage: .road, numberFormatStyle: .number).attributed) | |
let unitContainer = AttributeContainer.measurement(.unit) | |
let colorContainer = AttributeContainer.foregroundColor(.white) | |
resultString.replaceAttributes(unitContainer, with: colorContainer) | |
var resultStringCopy = resultString | |
// The closure will be called multiple times, and $0.value will be nil or not depending on if it's in the color range or not | |
resultString.transformingAttributes(AttributeScopes.UIKitAttributes.ForegroundColorAttribute.self) { | |
if $0.value == nil { | |
resultString.removeSubrange($0.range) | |
} else { | |
resultStringCopy.removeSubrange($0.range) | |
} | |
} | |
return (resultStringCopy, resultString) | |
} | |
} | |
print (35.0.formatElevation()) | |
//(40 { | |
// Foundation.MeasurementAttribute = value | |
// Foundation.NumberFormatPart = integer | |
//}, m { | |
// NSColor = UIExtendedGrayColorSpace 1 1 | |
//}) | |
// |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment