Skip to content

Instantly share code, notes, and snippets.

@asaday
Last active October 9, 2018 11:40
Show Gist options
  • Save asaday/d2704459bf9d8943b89e6033fcf97819 to your computer and use it in GitHub Desktop.
Save asaday/d2704459bf9d8943b89e6033fcf97819 to your computer and use it in GitHub Desktop.
extension String {
func attributed(attributes: [NSAttributedString.Key: Any]? = nil, font: UIFont? = nil, color: UIColor? = nil, base: CGFloat? = nil, lineHeight: CGFloat? = nil) -> NSAttributedString {
var atb = attributes ?? [:]
if let v = base { atb[.baselineOffset] = v }
if let v = font { atb[.font] = v }
if let v = color { atb[.foregroundColor] = v }
if let v = lineHeight {
let ps = NSMutableParagraphStyle()
ps.lineBreakMode = .byTruncatingTail
ps.minimumLineHeight = v
ps.maximumLineHeight = v
atb[.paragraphStyle] = ps
}
return NSMutableAttributedString(string: self, attributes: atb)
}
func imageAttributed(attributes: [NSAttributedString.Key: Any]? = nil, width: CGFloat? = nil, height: CGFloat? = nil, base: CGFloat? = nil) -> NSAttributedString {
guard let image = UIImage(named: self) else { return NSAttributedString() }
return image.attributed(attributes: attributes, width: width, height: height, base: base)
}
}
extension UIImage {
func attributed(attributes: [NSAttributedString.Key: Any]? = nil, width: CGFloat? = nil, height: CGFloat? = nil, base: CGFloat? = nil) -> NSAttributedString {
var rc = CGRect(origin: .zero, size: size)
if let v = width, height == nil && size.width > 0 { rc.size.width = v; rc.size.height = size.height / size.width * v }
if let v = height, width == nil && size.height > 0 { rc.size.height = v; rc.size.width = size.width / size.height * v }
if let w = width, let h = height { rc.size = CGSize(width: w, height: h) }
let attach = NSTextAttachment()
attach.image = self
attach.bounds = rc
let s = NSMutableAttributedString(attachment: attach)
var atb = attributes ?? [:]
if let v = base { atb[.baselineOffset] = v }
s.addAttributes(atb, range: NSRange(location: 0, length: 1))
return s
}
}
func + (left: NSAttributedString?, right: NSAttributedString) -> NSAttributedString {
guard let v = left else { return NSMutableAttributedString(attributedString: right) }
let s = v as? NSMutableAttributedString ?? NSMutableAttributedString(attributedString: v)
s.append(right)
return s
}
func += (left: inout NSAttributedString?, right: NSAttributedString) {
guard let v = left else { left = NSMutableAttributedString(attributedString: right); return }
let s = v as? NSMutableAttributedString ?? NSMutableAttributedString(attributedString: v)
s.append(right)
left = s
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment