2015-01-31 53 views
2

在異步線程或圖像緩存庫(如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)) 
    } 
+0

你,你知道如何解決它的範圍是多少?我有同樣的問題。 – HusseinB 2015-04-29 07:26:31

回答

5

NSTextAttachmentimage設置後,您需要強制的textView內容令人耳目一新。對於您可以使用textView.layoutManager's方法invalidateDisplayCharacterRange,其中range - 是您NSTextAttachement串

+0

你有我的upvote。感謝您指點我正確的方向。 -setNeedsDisplay爲我工作。 僅供參考,我使用的是UILabel。 – 2016-07-05 07:55:55

+0

@PrinceiPhone嗨,你可以在這裏分享你的代碼,我不是很清楚。 – Raniys 2016-10-26 01:27:19

+0

@Raniys我發佈了我的代碼 – 2016-10-26 06:35:01

0

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

非常感謝你,你是我的超級男人 – Raniys 2016-10-27 09:29:02

+0

高興地幫助:) – 2016-10-28 09:59:16