写图文混排时会遇到一个问题,我的图片是从网络上下载的,所以预先不知道图片的大小,但是NSTextAttachment是需要设定大小的,所以一开始就用的placeholder图片的大小,等图片下载完成候再更新NSTextAttachment的bounds。
UIImage*image = [UIImageimageNamed:@"placeholder.png"];
NSTextAttachment*imgAttachment = [[NSTextAttachmentalloc]init];
imgAttachment.image = image;
CGSizeimageSize =CGSizeMake(SCREEN_WIDTH-10,200);
imgAttachment.bounds =CGRectMake(0,0, imageSize.width, imageSize.height);
NSMutableAttributedString*imgAttributedString = [[NSMutableAttributedStringalloc]initWithAttributedString:[NSAttributedStringattributedStringWithAttachment:imgAttachment]];
[imgAttributedString addAttributes:self.tagAttributeDictionary[@"img"] range:NSMakeRange(0, imgAttributedString.length)];
[attributedString appendAttributedString:imgAttributedString];
NSURL*imgURL = [[NSURLalloc]initWithString:[element objectForKey:@"src"]];
[_sdManager downloadImageWithURL:(NSURL*)imgURL options:0progress:^(NSIntegerreceivedSize,NSIntegerexpectedSize) {
} completed:^(UIImage*image,NSError*error, SDImageCacheType cacheType,BOOLfinished,NSURL*imageURL) {
imgAttachment.bounds =CGRectMake(0,0, SCREEN_WIDTH-10, image.size.height/(image.size.width/(SCREEN_WIDTH-10)));
imgAttachment.image = image;
}];
但是当图片载入完成后,图片的大小还是原来的placeholder图片的大小,并没有按照设定后的大小显示,但是你如果重新退出这个ViewController再进入的话,图片神奇般的重新显示了。所以十有八九是TextView没有刷新的缘故了。如果调用textView的setNeedsLayout是没有用的,这个方法的用途是用来刷新subView的,对于TextView中的内容布局是没有影响的。
所以我们要用到的是CoreText中的NSLayoutManager,先看一下我们要用到的方法
invalidateLayoutForCharacterRange:actualCharacterRange:
定义 Invalidates the layout information for the glyphs mapped to the given range of characters.
这个方法会调用下面的方法
1 imageForBounds:textContainer:characterIndex: will be called again.
2 attachmentBoundsForTextContainer:[…]Index: will be called again.
所以调用TextView的LayoutManager的这个方法的话可以使TextAttachment的大小刷新,我们利用delegate,每当图片载入完成,调用delegate的方法去刷新textView,这样就能够让图片正常显示了。
NSURL*imgURL = [[NSURLalloc]initWithString:[element objectForKey:@"src"]];
[_sdManager downloadImageWithURL:(NSURL*)imgURL options:0progress:^(NSIntegerreceivedSize,NSIntegerexpectedSize) {
} completed:^(UIImage*image,NSError*error, SDImageCacheType cacheType,BOOLfinished,NSURL*imageURL) {
imgAttachment.bounds =CGRectMake(0,0, SCREEN_WIDTH-10, image.size.height/(image.size.width/(SCREEN_WIDTH-10)));
DebugLog(@"%f %f",imgAttachment.bounds.size.width,imgAttachment.bounds.size.height);
imgAttachment.image = image;
[self.delegate refreshTextViewAtRange:range];
}];
网友评论