UITextView實現圖文混排效果,uitextview圖文

來源:互聯網
上載者:User

UITextView實現圖文混排效果,uitextview圖文

用UITextView實現圖文混排效果的展示,首先要禁用UITextView的編輯功能,將屬性editable設定為NO

1.首先建立一個NSTextAttachment對象,這個對象有一個image屬性,可以將需要顯示的圖片賦值給這個屬性

NSTextAttachment *attachment = [[NSTextAttachment alloc] init];attachment.image = [UIImage imageNamed:@"imageName"];

2.將attachment對象轉換成屬性字串,以便之後將圖片顯示在文本中

NSMutableAttributedString *attachmentString = (NSMutableAttributedString *)[NSAttributedString attributedStringWithAttachment:attachment];

3.將圖片插入文本

[_textView.textStorage appendAttributedString:attachmentString];

如果圖片插入的位置不是在文本末尾的話,可以用 insertAttributedString: atIndex: 這個方法

4.圖片的顯示預設是按照原大小進行渲染,如果對映像大小有要求,需要調整映像大小的話,可以建立一個NSTextAttachment的子類,然後實現NSTextAttachmentContainer協議的這個方法

- (CGRect)attachmentBoundsForTextContainer:(NSTextContainer *)textContainer proposedLineFragment:(CGRect)lineFrag glyphPosition:(CGPoint)position characterIndex:(NSUInteger)charIndex;

這個方法會返回一個attachment的CGRect,如果需要調整attachment的大小,可以在這裡面進行,也可以在裡面限制attachment的大小

5.對於UITextView中的圖片,如果想要點擊效果的話,可以實現UITextViewDelegate這個協議裡面的方法

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

具體的點擊效果可以寫在上面這個方法中,最後的傳回值為YES,則圖片可以被複製、儲存,傳回值NO則不能,但是都不會影響返回之前的其他動作

6.對文字和圖片的其他展示效果,可以用NSAttributedString來實現

7.如果想要實現即時編輯長圖文的話,同樣也是先將圖片轉成attachment,然後在進行相同的操作就可以了,但是要先將textView的editable屬性改成YES

下面是我做好的圖文混排效果展示

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.