【发布时间】:2012-10-27 03:50:29
【问题描述】:
在我的应用程序中,我有一个 UITextView 和文本视图正下方的按钮,用于在编辑时将照片插入到 UITextView。
我的要求是用户用户能够在其中编辑文本,并在需要时插入图像。
类似于 StackOverflow 自己的应用程序UITextView:
【问题讨论】:
标签: iphone objective-c ipad uiimageview uitextview
在我的应用程序中,我有一个 UITextView 和文本视图正下方的按钮,用于在编辑时将照片插入到 UITextView。
我的要求是用户用户能够在其中编辑文本,并在需要时插入图像。
类似于 StackOverflow 自己的应用程序UITextView:
【问题讨论】:
标签: iphone objective-c ipad uiimageview uitextview
您可以将图像视图添加为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];
【讨论】:
如果您仅将其添加为子视图,则某些文本可以位于图像“后面”。 所以添加将“告诉”文本的代码,图像的那个区域是不可访问的:
UIBezierPath *exclusionPath = [UIBezierPath bezierPathWithRect:CGRectMake(CGRectGetMinX(imageView.frame),
CGRectGetMinY(imageView.frame), CGRectGetWidth(imageView.frame),
CGRectGetHeight(imageView.frame))];
textView.textContainer.exclusionPaths = @[exclusionPath];
【讨论】:
只需添加为 TextView 的子视图,如下所示..
[yourTextView addSubview:yourImageView];
【讨论】:
看看这个,ios-5-rich-text-editing-series。在 iOS 5 中,您可以插入图像并使用 HTML 文本。您可能必须使用 UIWebview 和 webkit。
您也可以通过EGOTextView 查询,它有很多富文本编辑功能。
【讨论】:
创建 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;
}
}
【讨论】: