我使用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;
}
感谢您的帮助:)
答案 0 :(得分:0)
[textView.layoutManager invalidateDisplayForCharacterRange:characterRange];
答案 1 :(得分:-1)
[textView.layoutManager invalidateDisplayForCharacterRange:characterRange];//refresh display
[textView.layoutManager invalidateLayoutForCharacterRange:characterRange actualCharacterRange:NULL];//refresh layout