3 回答

TA貢獻1828條經驗 獲得超3個贊
現在絕對可以使用
+ (NSAttributedString *)attributedStringWithAttachment:(NSTextAttachment *)attachment
請參閱此處的 Apple文檔
這個例子取自另一個答案:
UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(0,0,140,140)];
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:@"before after"];
NSTextAttachment *textAttachment = [[NSTextAttachment alloc] init];
textAttachment.image = [UIImage imageNamed:@"sample_image.jpg"];
CGFloat oldWidth = textAttachment.image.size.width;
//I'm subtracting 10px to make the image display nicely, accounting
//for the padding inside the textView
CGFloat scaleFactor = oldWidth / (textView.frame.size.width - 10);
textAttachment.image = [UIImage imageWithCGImage:textAttachment.image.CGImage scale:scaleFactor orientation:UIImageOrientationUp];
NSAttributedString *attrStringWithImage = [NSAttributedString attributedStringWithAttachment:textAttachment];
[attributedString replaceCharactersInRange:NSMakeRange(6, 1) withAttributedString:attrStringWithImage];
textView.attributedText = attributedString;
使用上面的代碼將在iOS 7+上的UITextView中為您提供帶有文本的圖像。您可以根據需要/顯示屬性文本的樣式,并可能設置圖像的寬度以確保它適合您的textView(以及設置您自己的寬高比/比例首選項)
這是一個快速測試圖像:
- 3 回答
- 0 關注
- 1003 瀏覽
添加回答
舉報