Added asychronous behavior to adding image.

This commit is contained in:
Kevin G Christiano 2019-08-27 16:28:19 -04:00
parent f73d5e73a5
commit c7501f9cd6

View File

@ -257,7 +257,14 @@ public typealias ActionBlock = () -> ()
case "icon":
let fontSize = attribute["size"] as? CGFloat ?? label.font.pointSize
let iconName = attribute["iconName"] as? String ?? "externalLink"
let imageAttachment = Label.getTextAttachmentImage(name: iconName, dimension: fontSize)
let imageURL = attribute["image"] as? String
let imageAttachment: NSTextAttachment
if let url = imageURL, let label = label as? Label {
imageAttachment = Label.getTextAttachmentFrom(url: url, dimension: fontSize, label: label)
} else {
imageAttachment = Label.getTextAttachmentImage(name: iconName, dimension: fontSize)
}
let mutableString = NSMutableAttributedString()
let space = NSAttributedString(string: " ")
@ -440,6 +447,12 @@ public typealias ActionBlock = () -> ()
self.attributedText = mutableString
}
/*
Retrieves an NSTextAttachment for NSAttributedString that is prepped to be inserted with the text.
- parameter name: The Asset name of the image. DEFAULT: "externalLink"
- parameter dimension: length of the height and width of the image. Will be 80% the passed magnitude.
*/
static func getTextAttachmentImage(name: String = "externalLink", dimension: CGFloat) -> NSTextAttachment {
let dimension = round(dimension * 0.8)
@ -450,6 +463,24 @@ public typealias ActionBlock = () -> ()
return imageAttachment
}
static func getTextAttachmentFrom(url: String, dimension: CGFloat, label: Label) -> NSTextAttachment {
let imageAttachment = NSTextAttachment()
imageAttachment.bounds = CGRect(x: 0, y: 0, width: dimension, height: dimension)
DispatchQueue.main.async {
guard let url = URL(string: url),
let data = try? Data(contentsOf: url)
else { return }
imageAttachment.image = UIImage(data: data)
label.setNeedsDisplay()
}
return imageAttachment
}
}
// MARK: - Atomization