为UITableViewCell加载NSTextAttachment的图像异步

时间:2015-01-31 22:50:45

标签: ios uitableview nstextattachment

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

3 个答案:

答案 0 :(得分:5)

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

答案 1 :(得分:2)

您可以使用这个来显示带有属性字符串的远程图像: https://github.com/namanhams/RemoteImageTextAttachment

答案 2 :(得分:1)

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