Swift compatible NSAttributedString
builder.
The main idea behind the implementation is that in Swift 4 there is a new NSAttributedStringKey
which is used for attributed string keys by String API.
So we can create a generic extension for [NSAttributedStringKey: Any]
dictionary:
extension Dictionary where Key == NSAttributedStringKey, Value == Any {
var font: UIFont { ... }
var foregroundColor: UIFont { ... }
...
}
Also we define a typealias for attributed dictionary just for convenience:
public typealias StringAttributes = [NSAttributedStringKey: Any]
let attributes = StringAttributes {
$0.foregroundColor = .red
$0.backgroundColor = .white
$0.link = URL(string: "http://github.com")
})
let string = NSAttributedString(string: "text", attributes: attributes)
let string = "text".with(StringAttributes {
$0.foregroundColor = .red
$0.backgroundColor = .white
$0.link = URL(string: "http://github.com")
})