针对UITableViewCell的NSTextAttachment加载映像异步
在异步线程或图像缓存库(如SDwebimage)中动态加载图像。下面的代码是我尝试过的,并且在从网络获取图像后不会重新绘制。针对UITableViewCell的NSTextAttachment加载映像异步
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))
}
的NSTextAttachment
image
设置后,您需要强制的textView
内容令人耳目一新。对于您可以使用textView.layoutManager's
方法invalidateDisplayCharacterRange
,其中range
- 是您NSTextAttachement串
你有我的upvote。感谢您指点我正确的方向。 -setNeedsDisplay为我工作。 仅供参考,我使用的是UILabel。 – 2016-07-05 07:55:55
@PrinceiPhone嗨,你可以在这里分享你的代码,我不是很清楚。 – Raniys 2016-10-26 01:27:19
@Raniys我发布了我的代码 – 2016-10-26 06:35:01
@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];
非常感谢你,你是我的超级男人 – Raniys 2016-10-27 09:29:02
高兴地帮助:) – 2016-10-28 09:59:16
你,你知道如何解决它的范围是多少?我有同样的问题。 – HusseinB 2015-04-29 07:26:31