为了账号安全,请及时绑定邮箱和手机立即绑定

如何在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(以及设置您自己的宽高比/比例首选项)


这是一个快速测试图像:

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

查看完整回答
反对 回复 2019-09-20
  • 3 回答
  • 0 关注
  • 954 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信