Ios 为UITableViewCell的NSTextAttachment加载图像异步

Ios 为UITableViewCell的NSTextAttachment加载图像异步,ios,uitableview,nstextattachment,Ios,Uitableview,Nstextattachment,在异步线程或图像缓存库(如SDwebimage)中动态加载图像。下面的代码是我尝试过的,在从网络获取图像后,它不会重新绘制 let mutableAttributedString = NSMutableAttributedString() if let _img = newsItem.img { var attachment = NSTextAttachment() attachment.bounds = CGRectMake(4, 4, exp

在异步线程或图像缓存库(如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))
    }

设置
NSTextAttachment
image
后,需要强制刷新
textView
内容。为此,您可以使用
textView.layoutManager的
方法
invalidateDisplayCharacterRange
,其中
range
-是我正在使用的NSTextAttachement子字符串的范围

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];

您可以使用此选项显示带有属性字符串的远程图像:

你知道怎么解决吗?我也有同样的问题,我投你一票。谢谢你给我指明了正确的方向-setNeedsDisplay为我工作。作为参考,我使用的是UILabel。@PrinceiPhone嗨,伙计,你能在这里分享你的代码吗,我不太清楚。我调用了self.textContainer?.layoutManager?.invalidateDisplay(forCharacterRange:self.range),但图像仍然不显示,@PrinceiPhone你在哪里更新cell.decl我有线程问题,图像未设置。不适用于tableview单元格包含文本附件完美答案,工作正常