亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在IOS中的UITextView中添加圖像和文本?

如何在IOS中的UITextView中添加圖像和文本?

iOS
一只名叫tom的貓 2019-09-20 15:25:14
我想在UITextView中添加文本和圖像。應根據文本和圖像的長度擴展textview。簡而言之,我想要做的是,當我從相機中捕獲圖像或從圖庫中選擇時,它應該顯示在UITextView中,我還應該能夠添加一些文本與該圖像類似于Facebook。我還附加了一個圖像, UITextView的外觀如何。
查看完整描述

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(以及設置您自己的寬高比/比例首選項)


這是一個快速測試圖像:

http://img1.sycdn.imooc.com//5d847f070001cd2706401136.jpg

查看完整回答
反對 回復 2019-09-20
  • 3 回答
  • 0 關注
  • 1003 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號