将图像添加到UITextView

时间:2012-11-07 05:46:09

标签: iphone objective-c ipad uiimageview uitextview

在我的应用中,我有一个UITextView和文本视图正下方的按钮,可以在编辑时将照片插入UITextView

我的要求是用户用户可以在其中编辑文本,并在需要时插入图像。

类似于StackOverflow的应用程序自己的UITextView

enter image description here

5 个答案:

答案 0 :(得分:18)

您可以将图片视图添加为UITextView的子视图。

使用图片创建imageView:

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

编辑:

为避免重叠使用(Thanks @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]; 

答案 1 :(得分:10)

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

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

textView.textContainer.exclusionPaths = @[exclusionPath];

答案 2 :(得分:1)

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

您还可以查看具有大量富文本编辑功能的EGOTextView

答案 3 :(得分:1)

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

    [yourTextView addSubview:yourImageView];

答案 4 :(得分: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;

    }
}