Skip to content

Instantly share code, notes, and snippets.

@novinfard
Created October 9, 2018 11:08
Show Gist options
  • Save novinfard/002ab0d05be4c562758f07e94ae167d4 to your computer and use it in GitHub Desktop.
Save novinfard/002ab0d05be4c562758f07e94ae167d4 to your computer and use it in GitHub Desktop.
[Set image for UILabel]
extension UILabel {
func set(image: UIImage, size: CGSize) {
let text = self.text ?? ""
let attachment = NSTextAttachment()
attachment.image = image
let verticalPosition = (font.capHeight - size.height).rounded() / 2
attachment.bounds = CGRect(x: 0, y: verticalPosition, width: size.width, height: size.height)
let attachmentStr = NSAttributedString(attachment: attachment)
let mutableAttributedString = NSMutableAttributedString()
mutableAttributedString.append(attachmentStr)
let textString = NSAttributedString(string: text, attributes: [.font: self.font])
mutableAttributedString.append(textString)
self.attributedText = mutableAttributedString
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment