Load Image async for NSTextAttachment for UITableViewCell

血红的双手。 提交于 2020-12-29 07:13:19

问题


Loading images dynamically in async thread or image cache library like SDwebimage. Below code is what I tried and it doesn't repaint after image fetched from network.

    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))
    }

回答1:


After image of NSTextAttachment was set, you need to force refreshing of textView contents. For that you can use textView.layoutManager's method invalidateDisplayCharacterRange, where range - is the range of your NSTextAttachement substring




回答2:


@Raniys I am using

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


来源:https://stackoverflow.com/questions/28257442/load-image-async-for-nstextattachment-for-uitableviewcell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!