Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
//: Playground - noun: a place where people can play
import UIKit
struct PriceTextProvider {
let basePrice: Double
let reducedPrice: Double
let vat: Double
}
struct PriceTextRenderOptions: OptionSetType {
let rawValue: Int
init(rawValue: Int) {
self.rawValue = rawValue
}
static let Base = PriceTextRenderOptions(rawValue: 1)
static let Reduced = PriceTextRenderOptions(rawValue: 2)
static let Vat = PriceTextRenderOptions(rawValue: 4)
static let BaseAndReduced = [Base, Reduced]
static let FullPrice = [Base, Reduced, Vat]
}
enum PriceTextContext {
case Normal, Short
}
class PriceTextRenderer {
let priceFormatter: NSNumberFormatter
let vatFormatter: NSNumberFormatter
init(priceFormatter: NSNumberFormatter, vatFormatter: NSNumberFormatter) {
self.priceFormatter = priceFormatter
self.vatFormatter = vatFormatter
}
func render(provider: PriceTextProvider, context: PriceTextContext, options: PriceTextRenderOptions) -> NSAttributedString {
let attributedPrice = NSMutableAttributedString(string: "")
let glue = context == .Normal ? "\n" : " "
if let basePrice = priceFormatter.stringFromNumber(NSNumber(double: provider.basePrice)) where options.contains(.Base) {
let a = NSAttributedString(string: basePrice, attributes: [NSForegroundColorAttributeName: UIColor.greenColor()])
attributedPrice.appendAttributedString(a)
}
if let reducedPrice = priceFormatter.stringFromNumber(NSNumber(double: provider.reducedPrice)) where options.contains(.Reduced) {
let a = NSAttributedString(string: "\(glue)\(reducedPrice)", attributes: [NSForegroundColorAttributeName: UIColor.redColor()])
attributedPrice.appendAttributedString(a)
}
if let vat = vatFormatter.stringFromNumber(NSNumber(double: provider.vat)) where options.contains(.Vat) {
let a = NSAttributedString(string: "\(glue)\(vat)")
attributedPrice.appendAttributedString(a)
}
return attributedPrice
}
}
let locale = NSLocale(localeIdentifier: "de_DE")
let priceFormatter = NSNumberFormatter()
priceFormatter.numberStyle = .CurrencyStyle
priceFormatter.locale = locale
let vatFormatter = NSNumberFormatter()
vatFormatter.numberStyle = .PercentStyle
vatFormatter.locale = locale
let renderer = PriceTextRenderer(priceFormatter: priceFormatter, vatFormatter: vatFormatter)
let provider = PriceTextProvider(basePrice: 20.00, reducedPrice: 15.00, vat: 0.19)
renderer.render(provider, context: .Normal, options: [.Base, .Reduced, .Vat])
renderer.render(provider, context: .Short, options: [.Base, .Reduced])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment