Created
October 9, 2018 11:08
-
-
Save novinfard/002ab0d05be4c562758f07e94ae167d4 to your computer and use it in GitHub Desktop.
[Set image for UILabel]
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 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