gpt4 book ai didi

ios - 如何在IOS的UITextView中添加图片和文字?

转载 作者:IT王子 更新时间:2023-10-29 07:40:17 31 4
gpt4 key购买 nike

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

enter image description here

最佳答案

这现在绝对有可能,使用

+ (NSAttributedString *)attributedStringWithAttachment:(NSTextAttachment *)attachment

请参阅 Apple 文档 here

这个例子取自另一个 answer :

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

这是一个快速测试图像:

enter image description here

关于ios - 如何在IOS的UITextView中添加图片和文字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24010035/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com