0

我使用 NSTextAttachment 来显示占位符图像。单击此图像时,我想显示另一张图像。我在 UItextView 委托方法中执行此操作:

-(BOOL)textView:(UITextView *)textView shouldInteractWithTextAttachment:(NSTextAttachment *)textAttachment inRange:(NSRange)characterRange

我遇到以下问题:点击(单击)图像并已进入委托方法,但图像不会立即更改。我尝试更改主队列中的图像并调用 setNeedsDisplay,但它仍然无法正常工作。请帮忙 :)

这是我的主要代码:

viewDidLoad:

NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:@"This is an example by @marcelofabri_"];

[attributedString addAttribute:NSLinkAttributeName
                         value:@"username://marcelofabri_"
                         range:[[attributedString string] rangeOfString:@"@marcelofabri_"]];

//first image
NSTextAttachment *textAttachment = [[NSTextAttachment alloc] init];
textAttachment.image = [UIImage imageNamed:@"sample_image.png"];
NSAttributedString *attrStringWithImage = [NSAttributedString attributedStringWithAttachment:textAttachment];

[attributedString appendAttributedString:attrStringWithImage];

self.textView.attributedText = attributedString;
self.textView.delegate = self;
self.textView.editable = NO;

UITextView 委托方法

-(BOOL)textView:(UITextView *)textView shouldInteractWithTextAttachment:(NSTextAttachment *)textAttachment inRange:(NSRange)characterRange{
UIImage *image  = textAttachment.image;

NSLog(@"width:%f , height:%f",image.size.width,image.size.height);
//change second image
  dispatch_async(dispatch_get_main_queue(), ^{                      

    textAttachment.image = [UIImage imageNamed:@"sample_image_1"];        
    [_textView setNeedsDisplay];
});

return true;
}

感谢帮助 :)

4

2 回答 2

1

经过一番挖掘,我发现 textview 可以通过使布局管理器无效来重绘图像

[textView.layoutManager invalidateDisplayForCharacterRange:characterRange];
于 2015-07-23T16:11:48.343 回答
-1
[textView.layoutManager invalidateDisplayForCharacterRange:characterRange];//refresh display
[textView.layoutManager invalidateLayoutForCharacterRange:characterRange actualCharacterRange:NULL];//refresh layout
于 2015-11-08T08:14:54.440 回答