Skip to content

Instantly share code, notes, and snippets.

@nolanw
Last active February 22, 2019 15:16
Show Gist options
  • Save nolanw/4cc88fac5c679156467929d04ea6d241 to your computer and use it in GitHub Desktop.
Save nolanw/4cc88fac5c679156467929d04ea6d241 to your computer and use it in GitHub Desktop.
An NSNumberFormatter for iOS that usefully implements attributedStringForObjectValue…
import Foundation
/// A number formatter that usefully implements `attributedString(for:withDefaultAttributes:)`, which iOS's NumberFormatter does not.
final class AttributedNumberFormatter: NumberFormatter {
override func attributedString(for obj: Any, withDefaultAttributes defaultAttributes: [NSAttributedString.Key : Any]? = nil) -> NSAttributedString? {
guard
let number = obj as? NSNumber,
let plain = string(from: number)
else { return nil }
let activeAttributes: [String: Any]?
switch (number, number.compare(0)) {
case (NSDecimalNumber.notANumber, _):
activeAttributes = textAttributesForNotANumber
case (kCFNumberPositiveInfinity, _):
activeAttributes = textAttributesForPositiveInfinity
case (kCFNumberNegativeInfinity, _):
activeAttributes = textAttributesForNegativeInfinity
case (_, .orderedSame):
activeAttributes = textAttributesForZero
case (_, .orderedAscending):
activeAttributes = textAttributesForNegativeValues
case (_, .orderedDescending):
activeAttributes = textAttributesForPositiveValues
}
// Seems to be how the Mac implementation works.
var attributes = defaultAttributes ?? [:]
for (k, v) in activeAttributes ?? [:] {
attributes[NSAttributedString.Key(k)] = v
}
return NSAttributedString(string: plain, attributes: attributes)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment