您的位置:首页 > 移动开发 > IOS开发

iOS中使用textView进行图文混排的上传与显示

2017-04-11 09:36 447 查看
在开始之前先看下效果图,是不是你想要的。



(1)首先在viewDidLoad中设置3个属性:

self.edgesForExtendedLayout = UIRectEdgeNone;
self.extendedLayoutIncludesOpaqueBars = NO;
self.modalPresentationCapturesStatusBarAppearance = NO;

    (2)然后获取图片,将图片显示在textView中:

    

#pragma mark - 相册代理
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {

UIImage *image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
//图片保存时每一张图片都要由一个名字,而相册和拍照中返回的info是不同的,但不管如何,都要想办法给每张图片一个唯一的名字
if (picker.sourceType ==UIImagePickerControllerSourceTypePhotoLibrary) {
//获取每张图片的id,用来作为保存在沙盒中的文件名
NSString *getsrc=[NSString stringWithFormat:@"%@",(NSString *)[info objectForKey:@"UIImagePickerControllerReferenceURL"]];
NSRange range={33,47};
self.imageName=[NSString stringWithFormat:@"%@.jpg",[getsrc substringWithRange:range]];
}
if (picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
self.imageName=[NSString stringWithFormat:@"%@.jpg",[[[info objectForKey:@"UIImagePickerControllerMediaMetadata"] objectForKey:@"{Exif}"] objectForKey:@"DateTimeDigitized"]];
self.imageName = [self.imageName stringByReplacingOccurrencesOfString:@" " withString:@""];
}

NSString *identifierForVendor = [[UIDevice currentDevice].identifierForVendor UUIDString];
self.imageName = [NSString stringWithFormat:@"%@%u.jpg",identifierForVendor,BARandomData];

//保存至沙盒
[self saveImage:image WithName:self.imageName];

//添加到附件中显示图片
[self addImageTextAttachmentImage:image];

[self dismissModalViewControllerAnimated:YES];

waitingDialog = [[MBProgressHUD alloc] init];
[self.view addSubview:waitingDialog];
[((MBProgressHUD *)waitingDialog) show:YES];

[self dismissViewControllerAnimated:YES completion:^(void){
[self onPostData];
}];

[self onPostData];
[self.messageInputView becomeFirstResponder];

}
      (3)对选中的图片进行截取大小,并重新设置textView的输入位置

//添加到附件中保存图片
- (void)addImageTextAttachmentImage:(UIImage *)image {
//适配屏幕宽度
UIImage *image1 = [image scaleToSize:CGSizeMake(MSW - 20, image.size.height * MSW / image.size.width)];
image = [self compressImage:image toMaxFileSize:0.2];
_image_h = image1.size.height;
_imageTextAttachment = [ImageTextAttachment new];

image=[_imageTextAttachment scaleImage:image withSize:CGSizeMake(MSW - 30,_image_h)];
//Set tag and image
_imageTextAttachment.image = image;

//Set image size
_imageTextAttachment.imageSize = CGSizeMake(MSW - 30,_image_h);

//Insert image image
[self.messageInputView.textStorage insertAttributedString:[NSAttributedString attributedStringWithAttachment:_imageTextAttachment]
atIndex:self.messageInputView.selectedRange.location];

//Move selection location
self.messageInputView.selectedRange = NSMakeRange(self.messageInputView.selectedRange.location + 1, self.messageInputView.selectedRange.length);

//设置输入内容的设置
[self setInitLocation];

_imageTextAttachment.imageTag = ImageTag;

//如果图片存在,则添加删除按钮
if (image != nil) {
//将图片添加到数组
[_itemArray addObject:image];

//在图片上增加删除按钮
UIButton *deleteBtn = [UIButton buttonWithType:UIButtonTypeCustom];
deleteBtn.frame = CGRectMake(image.size.width - 20, _messageInputView.contentSize.height - _image_h - 10, 30, 30);
[deleteBtn setImage:[UIImage imageNamed:@"Cricle_Delete"] forState:UIControlStateNormal];
deleteBtn.imageEdgeInsets = UIEdgeInsetsMake(5, -5, 10, -5);
deleteBtn.tag = _itemArray.count;
[deleteBtn addTarget:self action:@selector(deleteImageFromChooseView:) forControlEvents:UIControlEventTouchUpInside];
[_messageInputView addSubview:deleteBtn];

//把图片的位置存在数组
NSUInteger length = self.messageInputView.textStorage.length;
[_imageLenthArray addObject:@(length)];
}

}
      (4)最后,就是将所有的属性字符串转换成字符串,将图片位置遍历属性字符串,然后用和后台约定好的字符串类型替换掉就好。比如我这里和后台约定的是:图片的Url替换成{{p%lu}}     以下是两种判断方式,根据自己的需求即可。

#pragma mark - 将属性字符串转换成字符串
- (NSString *)textString
{
NSAttributedString *attStr = _messageInputView.attributedText;

NSMutableAttributedString *resutlAtt = [[NSMutableAttributedString alloc] initWithAttributedString:attStr];

__block NSUInteger index = 1;
__weak __typeof(self) weakSelf = self;
//枚举出所有的附件字符串
__block NSUInteger base = 0;

[attStr enumerateAttribute:NSAttachmentAttributeName inRange:NSMakeRange(0, attStr.length)
options:0
usingBlock:^(id value, NSRange range, BOOL *stop) {
if (value && [value isKindOfClass:[ImageTextAttachment class]]) {
NSString *p = [NSString stringWithFormat:@"{{p%lu}}", (unsigned long)index];
[resutlAtt replaceCharactersInRange:NSMakeRange(range.location + base, range.length)
withString:p];
if ([weakSelf.url isEqualToString:@""] || weakSelf.url == nil) {

weakSelf.url = [NSString stringWithFormat:@"%@=%@", p, _imgUrlArray[index - 1]];
} else {
weakSelf.url = [NSString stringWithFormat:@"%@,%@=%@", weakSelf.url, p, _imgUrlArray[index - 1]];

}

base += p.length - 1;
index++;
}
}];

//    [attStr enumerateAttributesInRange:NSMakeRange(0, attStr.length) options:NSAttributedStringEnumerationLongestEffectiveRangeNotRequired usingBlock:^(NSDictionary *attrs, NSRange range, BOOL *stop) {
//
//        //NSTextAttachment value类型 key-NSAttachment 从字典中取得那一个图片
//        //获取当前替换字符串的长度
//        __block NSUInteger base = 0;
//        NSTextAttachment *textAtt = attrs[@"NSAttachment"];
//        if (textAtt)
//        {
//            NSString *p = [NSString stringWithFormat:@"{{p%lu}}", (unsigned long)index];
//            [resutlAtt replaceCharactersInRange:NSMakeRange(range.location + base, range.length)
//                                     withString:p];
//            if ([weakSelf.url isEqualToString:@""] || weakSelf.url == nil) {
//
//                weakSelf.url = [NSString stringWithFormat:@"%@=%@", p, _imgUrlArray[index]];
//            } else {
//                weakSelf.url = [NSString stringWithFormat:@"%@,%@=%@", weakSelf.url, p, _imgUrlArray[index]];
//
//            }
//
//            base += p.length;
//            index++;
//
//        }
//
//    }];

DLog(@"---resutlAtt.string----- %@", resutlAtt.string)
return resutlAtt.string;

}

       (5)最后就大功告成了,你只需要将最后拼接好的哪一个字符串传给后台就好,然后在你需要显示这个内容的地方。将所获取的字符串转换成属性字符串就好,然后赋值给textView的attributeText就好。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  textview 图文混排
相关文章推荐