iOS常用iOS DeveloperiOS开发资料收集区

iOS富文本编辑器

2021-09-03  本文已影响0人  Appstore_花木源

实现:1、首次图文混编,输出是html标签的字符串;

            2、将html标签的内容再次编辑;

创建编辑控制器

.h文件

@property (nonatomic,strong)NSString *inHtmlString;

block是将编辑的内容返回上个页面操作

@property (nonatomic, copy)void (^postBlock)(NSString *htmlString);

.m文件

JavaScriptCore/JavaScriptCore.h

WebKit/WebKit.h

实现WKWebView的代理及相册的代理(懒得弄。用的系统相册)

NSString*_htmlString;//保存输出的富文本

    NSMutableArray*_imageArr;//保存添加的图片

@property (nonatomic, strong) WKWebView *webView;

加载写好的 .html文件 给个简易版本的即可

NSBundle *bundle = [NSBundle mainBundle];

    NSURL*indexFileURL = [bundleURLForResource:@"richTextEditor"withExtension:@"html"];

    [self.webView loadRequest:[NSURLRequest requestWithURL:indexFileURL]];

创建一个button 选择图片,给个点击事件

[btn1 addTarget:self action:@selector(addImage) forControlEvents:UIControlEventTouchUpInside];

创建一个button 保存html字符串,给个点击事件

[btn2 addTarget:self action:@selector(printHTML) forControlEvents:UIControlEventTouchUpInside];

- (void)printHTML{

    [self.webView evaluateJavaScript:@"document.getElementById('content').innerHTML" completionHandler:^(id _Nullable result, NSError * _Nullable error) {

        NSLog(@"html=%@",result);

        !self.postBlock?:self.postBlock(result);

        [self.navigationController popViewControllerAnimated:YES];

    }];

}

- (void)addImage{

    UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];

    imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;

    imagePickerController.delegate=self;

    [self presentViewController:imagePickerController animated:YES completion:nil];

}

实现相册代理方法

#pragma mark - ImagePickerController Delegate

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info

{

    UIImage * image = [info objectForKey:UIImagePickerControllerOriginalImage];

    NSData *data = UIImagePNGRepresentation(image);

    if(2*1024*1024>[datalength]) {

        data =UIImageJPEGRepresentation(image,0.6);

    }else{

    }

    UIImage*resultImage = [UIImageimageWithData:data];

    NSString *imagePath = [NSString stringWithFormat:@"%@", [info objectForKey:UIImagePickerControllerImageURL]];//本地图片路径

    [datawriteToFile:imagePathatomically:YES];

此处是将已添加的图片上传至你们的服务器

上传成功后执行

            NSString*url =服务器图片地址;

            NSString*script = [NSStringstringWithFormat:@"window.insertImage('%@', '%@')", imagePath, url];

            NSDictionary*dic =@{@"url":url,@"image":image,@"name":imagePath};

            [_imageArraddObject:dic];

            [self.webViewevaluateJavaScript:scriptcompletionHandler:^(id_Nullableresult,NSError*_Nullableerror) {

            }];

            [self dismissViewControllerAnimated:YES completion:nil];

}

上一篇下一篇

猜你喜欢

热点阅读