如何在IOS中的UITextView中添加图像和文本? [英] How to add image and text in UITextView in IOS?

查看:302
本文介绍了如何在IOS中的UITextView中添加图像和文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在UITextView中添加文本和图像。应根据文本和图像的长度扩展textview。简而言之,我想要做的是,当我从相机中捕获图像或从图库中选择时,它应该显示在UITextView中,我还应该能够添加一些类似于Facebook的图像文本。我还附加了一个图像, UITextView的外观如何。

I want to add both text and image in UITextView. The textview should be expanded according to the length of the text and image. In short what I want to do is that when I capture an image from camera or pick from gallery then it should display in UITextView and I should also be able to add some text with that image similar to Facebook.I am also attaching an image that how the UITextView will look like.

推荐答案

现在绝对可以使用

+(NSAttributedString *)attributionStringWithAttachment:(NSTextAttachment *)附件

请参阅Apple文档这里

See Apple docs here

这个例子取自其他答案

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(以及设置您自己的宽高比/比例偏好)

Using the above code will get you an image with text inside a UITextView on iOS 7+. You can/show style the attributed text as you want it and probably set the width of the image to make sure it fits within your textView (as well as setting your own aspect ratio/scale preference)

这是一个快速测试图像:

Here's a quick test image:

这篇关于如何在IOS中的UITextView中添加图像和文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆