最近開發(fā)需求需要實現(xiàn)一個富文本編輯器,論壇搜索加科學(xué)上網(wǎng)之后得出功能比較齊全且應(yīng)用較多的兩個富文本編輯器分別是ZSSRichTextEditor和 WordPress-Editor-iOS。
從兩個編輯器的demo運行效果來看,ZSSRichTextEditor性能較差,并且文本內(nèi)容較多之后打字時頁面抖動嚴(yán)重,所以就選擇了從demo來看坑比較少的WordPress-Editor-iOS。
由于WordPress-Editor-iOS的oc版本從2017年底就不在更新了,所以有坑也只能自己解決,下面就開始講講我的踩坑之旅。
我遇到的坑主要分為以下幾種:
- 彈出鍵盤后頁面亂滾,光標(biāo)移出屏幕,無法定位
- 大圖加載失敗,頁面只展示一個小方塊,圖片無法展示
- 鍵盤彈出后不顯示工具欄
大坑之一: 彈出鍵盤后頁面亂滾,光標(biāo)移出屏幕,無法定位
論壇上用過WordPress-Editor-iOS的開發(fā)這都反饋頁面亂滾的情況,由于WordPress-Editor-iOS是js有oc交互的,所以就頁面滾動問題咨詢了h5 同事,發(fā)現(xiàn)h5在獲取焦點后,彈出鍵盤會自動滾動到焦點位置,然而在WPEditorView.m文件中的scrollToCaretAnimated:(BOOL)animated 方法也會使頁面滑動,從而導(dǎo)致頁面滑動出錯,禁用該方法即可
- (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的圖片回調(diào)方法如下
- (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取出的原圖數(shù)據(jù)太大,加載出現(xiàn)問題,直接從info里面取數(shù)據(jù)就可以了。
- (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中有標(biāo)題輸入控件,但是我的項目不需要輸入標(biāo)題,所以我在editor.html文件中刪掉了標(biāo)題控件,然后坑就出現(xiàn)了,每次打開編輯器的時候鍵盤自動彈出但是并不出現(xiàn)富文本工具欄。查看js代碼發(fā)現(xiàn)編輯器運行時會自動獲取標(biāo)題控件的焦點,然而標(biāo)題控件并不支持富文本編輯,所以剛打開編輯器的時候鍵盤彈出不帶工具欄。在editor.html文件中做如下修改,自動獲取文本輸入?yún)^(qū)的焦點
$(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,現(xiàn)已補上。
demo還有很多地方需要優(yōu)化,有想法的同學(xué)歡迎評論區(qū)回復(fù)。
友情提示:demo運行前需要pod install 一下呦。
[demo](https://github.com/Fairy-happy/WordPress-Editor-iOS-optimization)
相關(guān)鏈接:https://github.com/nnhubbard/ZSSRichTextEditor
https://github.com/wordpress-mobile/WordPress-Editor-iOS