Last active
April 23, 2017 10:39
-
-
Save mariabernis/c80ebee4ba39d6867deda94adb56928c to your computer and use it in GitHub Desktop.
This file contains hidden or 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 { | |
| typealias Attributes = [String : NSObject] | |
| convenience init( | |
| prefix: String? = nil, | |
| prefixAttributes: Attributes? = nil, | |
| string: String, | |
| stringAttributes: Attributes, | |
| suffix: String? = nil, | |
| suffixAttributes: Attributes? = nil | |
| ) { | |
| let attributedString = NSMutableAttributedString() | |
| if let prefix = prefix { | |
| let attributtedPrefix = NSAttributedString(string: prefix, attributes: prefixAttributes) | |
| attributedString.append(attributtedPrefix) | |
| } | |
| let attributtedContent = NSAttributedString(string: string, attributes: stringAttributes) | |
| attributedString.append(attributtedContent) | |
| if let suffix = suffix { | |
| let attributtedSuffix = NSAttributedString(string: suffix, attributes: suffixAttributes) | |
| attributedString.append(attributtedSuffix) | |
| } | |
| self.init(attributedString: attributedString) | |
| } | |
| // Similarly for icon+text structures, where text wraps around the icon when multi-line | |
| // we also use NSAttributedString: | |
| convenience init( | |
| prefixIcon: UIImage? = nil, | |
| prefixAttributes: Attributes? = nil, | |
| string: String, | |
| stringAttributes: Attributes | |
| ) { | |
| let attributedString = NSMutableAttributedString() | |
| if let prefixIcon = prefixIcon { | |
| let attachment = NSTextAttachment() | |
| attachment.image = prefixIcon | |
| let attributedAttachment = NSAttributedString(attachment: attachment) | |
| let attributtedPrefix = NSMutableAttributedString(attributedString: attributedAttachment) | |
| if let prefixAttributes = prefixAttributes { | |
| // prefixAttributes is usually an offset to align | |
| // the icon with the text properly, sth like [NSBaselineOffsetAttributeName: -2] | |
| // We make sure to apply the styles only to the prefix | |
| attributtedPrefix.addAttributes( | |
| prefixAttributes, | |
| range: NSRange(location: 0, length: attributedAttachment.length) | |
| ) | |
| } | |
| attributedString.append(attributtedPrefix) | |
| } | |
| let attributtedContent = NSAttributedString(string: string, attributes: stringAttributes) | |
| attributedString.append(attributtedContent) | |
| self.init(attributedString: attributedString) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment