Skip to content

Instantly share code, notes, and snippets.

@mariabernis
Last active April 23, 2017 10:39
Show Gist options
  • Select an option

  • Save mariabernis/c80ebee4ba39d6867deda94adb56928c to your computer and use it in GitHub Desktop.

Select an option

Save mariabernis/c80ebee4ba39d6867deda94adb56928c to your computer and use it in GitHub Desktop.
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