最近开发需求需要实现一个富文本编辑器,论坛搜索加科学上网之后得出功能比较齐全且应用较多的两个富文本编辑器分别是ZSSRichTextEditor和 WordPress-Editor-iOS。
从两个编辑器的demo运行效果来看,ZSSRichTextEditor性能较差,并且文本内容较多之后打字时页面抖动严重,所以就选择了从demo来看坑比较少的WordPress-Editor-iOS。
由于WordPress-Editor-iOS的oc版本从2017年底就不在更新了,所以有坑也只能自己解决,下面就开始讲讲我的踩坑之旅。
我遇到的坑主要分为以下几种:
- 弹出键盘后页面乱滚,光标移出屏幕,无法定位
- 大图加载失败,页面只展示一个小方块,图片无法展示
- 键盘弹出后不显示工具栏
大坑之一: 弹出键盘后页面乱滚,光标移出屏幕,无法定位
论坛上用过WordPress-Editor-iOS的开发这都反馈页面乱滚的情况,由于WordPress-Editor-iOS是js有oc交互的,所以就页面滚动问题咨询了h5 同事,发现h5在获取焦点后,弹出键盘会自动滚动到焦点位置,然而在WPEditorView.m文件中的scrollToCaretAnimated:(BOOL)animated 方法也会使页面滑动,从而导致页面滑动出错,禁用该方法即可
- (void)scrollToCaretAnimated:(BOOL)animated
{
BOOL notEnoughInfoToScroll = self.caretYOffset == nil || self.lineHeight == nil;
if (notEnoughInfoToScroll) {
return;
}
CGRect viewport = [self viewport];
CGFloat caretYOffset = [self.caretYOffset floatValue];
CGFloat lineHeight = [self.lineHeight floatValue];
CGFloat offsetBottom = caretYOffset + lineHeight;
BOOL mustScroll = (caretYOffset < viewport.origin.y
|| offsetBottom > viewport.origin.y + CGRectGetHeight(viewport));
if (mustScroll) {
// DRM: by reducing the necessary height we avoid an issue that moves the caret out
// of view.
//
CGFloat necessaryHeight = viewport.size.height / 2;
// DRM: just make sure we don't go out of bounds with the desired yOffset.
//
caretYOffset = MIN(caretYOffset,
self.webView.scrollView.contentSize.height - necessaryHeight);
CGRect targetRect = CGRectMake(0.0f,
caretYOffset,
CGRectGetWidth(viewport),
necessaryHeight);
[self.webView.scrollView scrollRectToVisible:targetRect animated:animated];
}
}
同时在WPEditorView.m文件中进行以下代码的添加:
-(void)swizzleMethod:(SEL)origSel from:(Class)origClass toMethod:(SEL)toSel from:(Class)toClass{
Method origMethod = class_getInstanceMethod(origClass, origSel);
Method newMethod = class_getInstanceMethod(toClass, toSel);
method_exchangeImplementations(origMethod, newMethod);
}
-(void)disableMethod:(SEL)sel onClass:(Class)cl{
[self swizzleMethod:sel from:cl toMethod:@selector(doNothing) from:[self class]];
}
-(void)enableMethod:(SEL)method onClass:(Class)cl {
[self swizzleMethod:@selector(doNothing) from:[self class] toMethod:method from:cl];
}
-(void)doNothing{
}
- (void)keyboardWillShow:(NSNotification *)notification
{
[self disableMethod:@selector(setContentOffset:) onClass:[UIScrollView class]];
[self refreshKeyboardInsetsWithShowNotification:notification];
}
-(void)keyboardShown {
[self enableMethod:@selector(setContentOffset:) onClass:[UIScrollView class]];
}
- (void)keyboardDidShow:(NSNotification *)notification
{
BOOL isiOSVersionEarlierThan8 = [WPDeviceIdentification isiOSVersionEarlierThan8];
if (isiOSVersionEarlierThan8) {
// PROBLEM: under iOS 7, it seems that setting the proper insets in keyboardWillShow: is not
// enough. We were having trouble when adding images, where the keyboard would show but the
// insets would be reset to {0, 0, 0, 0} between keyboardWillShow: and keyboardDidShow:
//
// HOW TO TEST:
//
// - launch the WPiOS app under iOS 7.
// - set a title
// - make sure the virtual keyboard is up
// - add some text and on the same line add an image
// - once the image is added tap once on the content field to make the keyboard come back up
// (do this before the upload finishes).
//
// WORKAROUND: we just set the insets again in keyboardDidShow: for iOS 7
//
[self refreshKeyboardInsetsWithShowNotification:notification];
}
[self keyboardShown];
}
大坑之二:大图加载失败,页面只展示一个小方块,图片无法展示
demo的图片回调方法如下
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
[self.navigationController dismissViewControllerAnimated:YES completion:^{
NSURL *assetURL = info[UIImagePickerControllerReferenceURL];
[self addAssetToContent:assetURL];
}];
}
- (void)addAssetToContent:(NSURL *)assetURL
{
PHFetchResult *assets = [PHAsset fetchAssetsWithALAssetURLs:@[assetURL] options:nil];
if (assets.count < 1) {
return;
}
PHAsset *asset = [assets firstObject];
if (asset.mediaType == PHAssetMediaTypeVideo) {
[self addVideoAssetToContent:asset];
} if (asset.mediaType == PHAssetMediaTypeImage) {
[self addImageAssetToContent:asset];
}
}
- (void)addImageAssetToContent:(PHAsset *)asset
{
PHImageRequestOptions *options = [PHImageRequestOptions new];
options.synchronous = NO;
options.networkAccessAllowed = YES;
options.resizeMode = PHImageRequestOptionsResizeModeExact;
options.version = PHImageRequestOptionsVersionCurrent;
options.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
[[PHImageManager defaultManager] requestImageDataForAsset:asset
options:options
resultHandler:^(NSData * _Nullable imageData, NSString * _Nullable dataUTI, UIImageOrientation orientation, NSDictionary * _Nullable info) {
[self addImageDataToContent:imageData];
}];
}
- (void)addImageDataToContent:(NSData *)imageData
{
NSString *imageID = [[NSUUID UUID] UUIDString];
NSString *path = [NSString stringWithFormat:@"%@/%@.jpg", NSTemporaryDirectory(), imageID];
[imageData writeToFile:path atomically:YES];
dispatch_async(dispatch_get_main_queue(), ^{
[self.editorView insertLocalImage:[[NSURL fileURLWithPath:path] absoluteString] uniqueId:imageID];
});
NSProgress *progress = [[NSProgress alloc] initWithParent:nil userInfo:@{ @"imageID": imageID, @"url": path }];
progress.cancellable = YES;
progress.totalUnitCount = 100;
NSTimer * timer = [NSTimer scheduledTimerWithTimeInterval:0.1
target:self
selector:@selector(timerFireMethod:)
userInfo:progress
repeats:YES];
[progress setCancellationHandler:^{
[timer invalidate];
}];
self.mediaAdded[imageID] = progress;
}
通过PHAsset取出的原图数据太大,加载出现问题,直接从info里面取数据就可以了。
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
[self.navigationController dismissViewControllerAnimated:YES completion:^{
NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
if ([type isEqualToString:@"public.image"]) {
UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
NSData * imageData = UIImageJPEGRepresentation(image,0.7);
[self addImageDataToContent:imageData];
} else {
//视频
NSURL *assetURL = info[UIImagePickerControllerReferenceURL];
[self addAssetToContent:assetURL];
}
}];
}
大坑之三:键盘弹出后不显示工具栏
由于demo中有标题输入控件,但是我的项目不需要输入标题,所以我在editor.html文件中删掉了标题控件,然后坑就出现了,每次打开编辑器的时候键盘自动弹出但是并不出现富文本工具栏。查看js代码发现编辑器运行时会自动获取标题控件的焦点,然而标题控件并不支持富文本编辑,所以刚打开编辑器的时候键盘弹出不带工具栏。在editor.html文件中做如下修改,自动获取文本输入区的焦点
$(document).ready(function() {
ZSSEditor.init(callbacker, logger);
$('#zss_field_content').focus().on('click','img',function(e){
e.preventDefault();
return false;
});
});
同时,在WPEditorView.m文件中做如下修改
- (void)disableEditing
{
if (!self.sourceView.hidden) {
[self showVisualEditor];
}
// [self.titleField disableEditing];
[self.contentField disableEditing];
// [self.sourceViewTitleField setEnabled:NO];
[self.sourceView setEditable:NO];
}
- (void)enableEditing
{
// [self.titleField enableEditing];
[self.contentField enableEditing];
// [self.sourceViewTitleField setEnabled:YES];
[self.sourceView setEditable:YES];
}
2018.7.31更新
最近工作比较忙,没有及时上传demo,现已补上。
demo还有很多地方需要优化,有想法的同学欢迎评论区回复。
友情提示:demo运行前需要pod install 一下呦。
[demo](https://github.com/Fairy-happy/WordPress-Editor-iOS-optimization)
相关链接:https://github.com/nnhubbard/ZSSRichTextEditor
https://github.com/wordpress-mobile/WordPress-Editor-iOS