12

In my app I have a UITextView and a button just below the text view to insert a photo into the UITextView while editing.

My requirement is that the user user is able to edit the text within, and insert images when needed.

Similar to StackOverflow's app's own UITextView:

enter image description here

4

5 回答 5

18

您可以将图像视图添加为UITextView.

创建一个带有图像的 imageView:

UIImageView *imageView = [[UIImageView alloc] initWithImage:yourImage];
[imageView setFrame:yourFrame];
[yourTextView addSubview:imageView];

编辑:

为了避免重叠使用(感谢@chris):

CGRect aRect = CGRectMake(156, 8, 16, 16);
[imageView setFrame:aRect];
UIBezierPath *exclusionPath = [UIBezierPath bezierPathWithRect:CGRectMake(CGRectGetMinX(imageView.frame), CGRectGetMinY(imageView.frame), CGRectGetWidth(yourTextView.frame), CGRectGetHeight(imageView.frame))];
yourTextView.textContainer.exclusionPaths = @[exclusionPath];
[yourTextView addSubview:imageView]; 
于 2012-11-07T05:49:40.623 回答
10

如果仅将其添加为子视图,则某些文本可以位于图像“后面”。所以添加将“告诉”文本的代码,图像的该区域是不可访问的:

UIBezierPath *exclusionPath = [UIBezierPath    bezierPathWithRect:CGRectMake(CGRectGetMinX(imageView.frame),    
CGRectGetMinY(imageView.frame), CGRectGetWidth(imageView.frame), 
CGRectGetHeight(imageView.frame))];

textView.textContainer.exclusionPaths = @[exclusionPath];
于 2014-04-23T06:41:09.653 回答
1

看看这个,ios-5-rich-text-editing-series。在 iOS 5 中,您可以插入图像并使用 HTML 文本。您可能必须使用UIWebview和 webkit。

您还可以使用具有许多富文本编辑功能的EGOTextView进行检查。

于 2012-11-07T05:51:06.207 回答
1

只需添加为 TextView 的子视图,如下所示..

    [yourTextView addSubview:yourImageView];
于 2012-11-07T05:52:37.217 回答
0

创建 UITextView 的子类并覆盖此方法

- (void)paste:(id)sender 
{
    NSData *data = [[UIPasteboard generalPasteboard] dataForPasteboardType:@"public.png"];

    if (data) 
    {

        NSMutableAttributedString *attributedString = [[self attributedText] mutableCopy];

        NSTextAttachment *textAttachment = [[NSTextAttachment alloc] init];

        textAttachment.image = [UIImage imageWithData:data scale:5];

        NSAttributedString *attrStringWithImage = [NSAttributedString attributedStringWithAttachment:textAttachment];

        [attributedString replaceCharactersInRange:self.selectedRange withAttributedString:attrStringWithImage];

        self.attributedText = attributedString;

    }
    else
    {

        UIPasteboard *pasteBoard = [UIPasteboard generalPasteboard];

        NSAttributedString *text = [[NSAttributedString alloc] initWithString:pasteBoard.string];

        NSMutableAttributedString *attributedString = [self.attributedText mutableCopy];

        [attributedString replaceCharactersInRange:self.selectedRange withAttributedString:text];

        self.attributedText = attributedString;

    }
}
于 2015-05-12T11:17:02.357 回答