Skip to content

Instantly share code, notes, and snippets.

@carson-katri
Last active July 12, 2023 08:43
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save carson-katri/d398764a76a9b525e4a34e360cb70187 to your computer and use it in GitHub Desktop.
Save carson-katri/d398764a76a9b525e4a34e360cb70187 to your computer and use it in GitHub Desktop.
extension String {
func foregroundColor(_ color: UIColor) -> NSAttributedString {
NSAttributedString(string: self, attributes: [.foregroundColor : color])
}
func background(_ color: UIColor) -> NSAttributedString {
NSAttributedString(string: self, attributes: [.backgroundColor: color])
}
func underline(_ color: UIColor, style: NSUnderlineStyle = .single) -> NSAttributedString {
NSAttributedString(string: self, attributes: [.underlineColor: color, .underlineStyle: style.rawValue])
}
func font(_ font: UIFont) -> NSAttributedString {
NSAttributedString(string: self, attributes: [.font: font])
}
func shadow(_ shadow: NSShadow) -> NSAttributedString {
NSAttributedString(string: self, attributes: [.shadow: shadow])
}
var attributed: NSAttributedString {
NSAttributedString(string: self)
}
}
extension NSAttributedString {
func apply(_ attributes: [NSAttributedString.Key:Any]) -> NSAttributedString {
let mutable = NSMutableAttributedString(string: self.string, attributes: self.attributes(at: 0, effectiveRange: nil))
mutable.addAttributes(attributes, range: NSMakeRange(0, (self.string as NSString).length))
return mutable
}
func foregroundColor(_ color: UIColor) -> NSAttributedString {
self.apply([.foregroundColor : color])
}
func background(_ color: UIColor) -> NSAttributedString {
self.apply([.backgroundColor: color])
}
func underline(_ color: UIColor, style: NSUnderlineStyle = .single) -> NSAttributedString {
self.apply([.underlineColor: color, .underlineStyle: style.rawValue])
}
func font(_ font: UIFont) -> NSAttributedString {
self.apply([.font: font])
}
func shadow(_ shadow: NSShadow) -> NSAttributedString {
self.apply([.shadow:shadow])
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment