Skip to content

Instantly share code, notes, and snippets.

@maxchuquimia
Last active May 24, 2019 14:38
Show Gist options
  • Save maxchuquimia/734f722d80a339dc534d to your computer and use it in GitHub Desktop.
Save maxchuquimia/734f722d80a339dc534d to your computer and use it in GitHub Desktop.
Concatenate NSAttributedString in Swift without your code wrapping over multiple lines. Also adding images to attributed strings is supported!
func +(lhs: NSAttributedString, rhs: NSAttributedString) -> NSAttributedString {
let a = lhs.mutableCopy() as! NSMutableAttributedString
let b = rhs.mutableCopy() as! NSMutableAttributedString
a.appendAttributedString(b)
return a.copy() as! NSAttributedString
}
func +(lhs: NSAttributedString, rhs: String) -> NSAttributedString {
let a = lhs.mutableCopy() as! NSMutableAttributedString
let b = NSMutableAttributedString(string: rhs)
return a + b
}
func +(lhs: String, rhs: NSAttributedString) -> NSAttributedString {
let a = NSMutableAttributedString(string: lhs)
let b = lhs.mutableCopy() as! NSMutableAttributedString
return a + b
}
func +(lhs: NSAttributedString, rhs: UIImage) -> NSAttributedString {
let a = lhs.mutableCopy() as! NSMutableAttributedString
let b = NSTextAttachment()
b.image = rhs
return a + b
}
func +(lhs: UIImage, rhs: NSAttributedString) -> NSAttributedString {
let a = NSTextAttachment()
a.image = lhs
let b = rhs.mutableCopy() as! NSMutableAttributedString
return a + b
}
func +(lhs: NSAttributedString, rhs: NSTextAttachment) -> NSAttributedString {
let a = lhs.mutableCopy() as! NSMutableAttributedString
let b = NSAttributedString(attachment: rhs)
return a + b
}
func +(lhs: NSTextAttachment, rhs: NSAttributedString) -> NSAttributedString {
let a = NSAttributedString(attachment: lhs)
let b = rhs.mutableCopy() as! NSMutableAttributedString
return a + b
}
@rogpfreck
Copy link

Very useful. Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment