Skip to content

Instantly share code, notes, and snippets.

@pangers
Last active December 23, 2016 23:27
Show Gist options
  • Save pangers/9755d133925b8b61d0daef73a1449c0e to your computer and use it in GitHub Desktop.
Save pangers/9755d133925b8b61d0daef73a1449c0e to your computer and use it in GitHub Desktop.
extension NSAttributedString {
func align(_ alignment: NSTextAlignment) -> NSAttributedString {
//1
guard !string.isEmpty else { return self }
//2
let mutable = mutableCopy() as! NSMutableAttributedString
//3
let style = mutable.attribute(NSParagraphStyleAttributeName, at: 0, longestEffectiveRange: nil, in: NSMakeRange(0, string.characters.count)) as? NSParagraphStyle
//4
let pStyle = (style?.mutableCopy() as? NSMutableParagraphStyle) ?? NSMutableParagraphStyle()
//5
pStyle.alignment = alignment
//6
let attribute = [
NSParagraphStyleAttributeName : pStyle
]
//7
mutable.addAttributes(attribute, range: NSRange(location: 0, length: string.characters.count))
return mutable
}
}
//Example Usage
"Style me"
.toAttributedString()
.medium(sized: 16)
.colored(.orange)
.align(.center)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment