Last active
December 23, 2016 23:27
-
-
Save pangers/9755d133925b8b61d0daef73a1449c0e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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