[英]Load Image async for NSTextAttachment for UITableViewCell
在異步線程或圖像緩存庫(如 SDwebimage)中動態加載圖像。 下面的代碼是我嘗試過的,從網絡獲取圖像后它不會重新繪制。
let mutableAttributedString = NSMutableAttributedString()
if let _img = newsItem.img {
var attachment = NSTextAttachment()
attachment.bounds = CGRectMake(4, 4, expectedWidth, expectedWidth * _img.ratio)
dispatch_async(dispatch_get_main_queue(), { () -> Void in
attachment.image = UIImage(data: NSData(contentsOfURL: NSURL(string: _img.src)!)!)
})
mutableAttributedString.appendAttributedString(NSAttributedString(attachment: attachment))
}
后image
的NSTextAttachment
設置,您需要強制的刷新textView
內容。 為此,您可以使用textView.layoutManager's
方法invalidateDisplayCharacterRange
,其中range
- 是您的 NSTextAttachement 子字符串的范圍
您可以使用這個來顯示帶有屬性字符串的遠程圖像: https : //github.com/namanhams/RemoteImageTextAttachment
@Raniys 我正在使用
NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0ul);
dispatch_async(queue, ^{
NSURL *url = [NSURL URLWithString:[[NSString stringWithFormat:@"%@%@", [ServerURL stringByReplacingOccurrencesOfString:@"/api" withString:@""], iconsArr[i][@"icon"]] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
SDWebImageManager *manager = [SDWebImageManager sharedManager];
[manager downloadImageWithURL:url options:0 progress:NULL completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
attachment.image = image;
[cell.descL setNeedsDisplay];
}];
});
attachment.bounds = CGRectMake(0, -3, 12, 12);
NSAttributedString *attachmentString = [NSAttributedString attributedStringWithAttachment:attachment];
NSMutableAttributedString *myString = [[NSMutableAttributedString alloc] initWithAttributedString:attachmentString];
NSAttributedString *myText = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@" %@ \n", iconsArr[i][@"title"]]];
[myString appendAttributedString:myText];
[descStr appendAttributedString:myString];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.