问题描述
我有一个带有contentEditable div的UIWebView,以便实现某种富文本编辑器。我需要修剪副本和一旦用户选择任何文本,UIMenuController中的选项就会显示在Web视图中。
I have a UIWebView with a contentEditable div in order to implement some kind of rich text editor. I need to trimm the copy & cut options in the UIMenuController that appears in the web view once the user selects any piece of text.
网络上似乎有很多解决方案,但出于某种原因,不适用于我的场景。
我已经将UIWebView子类化并实现了 canPerformAction :( SEL)动作withSender:
删除副本并剪切,但一旦用户选择选择或全选,就会出现一个新菜单,显然,网页视图不会拦截此操作,没有调用canPerform方法。
I've subclassed the UIWebView and implemented the canPerformAction:(SEL)action withSender:
to remove the copy and cut, but once the user chooses "Select" or "Select All", a new menu appears, and apparently, the web view does not intercept this action and the canPerform method is not being called.
对于这种情况,有没有办法修剪动作?
Is there a way to trimm actions for this cases?
推荐答案
我将根据您的情况调整。
I will adapt another answer of mine for your case.
canPerformAction:
实际上是在内部调用 UIWebDocumentView
而不是 UIWebView
,您通常不能将其子类化。有一些运行时魔术,它是可能的。
The canPerformAction:
is actually called on the internal UIWebDocumentView
instead of the UIWebView
, which you cannot normally subclass. With some runtime magic, it's possible.
我们创建一个有一种方法的类:
We create a class which has one method:
@interface _SwizzleHelper : UIView @end
@implementation _SwizzleHelper
-(BOOL)canPerformAction:(SEL)action
{
//Your logic here
return NO;
}
@end
获得网络视图后你想控制它的动作,你迭代它的滚动视图的子视图,并采取 UIWebDocumentView
类。然后,我们动态地将上面创建的类的超类作为子视图的类(UIWebDocumentView - 但我们不能预先说明这是私有API),并将子视图的类替换为我们的类。
Once you have a web view which you want to control the actions of, you iterate its scroll view's subviews and take the UIWebDocumentView
class. We then dynamically make the superclass of the class we created above to be the subview's class (UIWebDocumentView - but we cannot say that upfront because this is private API), and replace the subview's class to our class.
#import "objc/runtime.h"
-(void)__subclassDocumentView
{
UIView* subview;
for (UIView* view in self.scrollView.subviews) {
if([[view.class description] hasPrefix:@"UIWeb"])
subview = view;
}
if(subview == nil) return; //Should not stop here
NSString* name = [NSString stringWithFormat:@"%@_SwizzleHelper", subview.class.superclass];
Class newClass = NSClassFromString(name);
if(newClass == nil)
{
newClass = objc_allocateClassPair(subview.class, [name cStringUsingEncoding:NSASCIIStringEncoding], 0);
if(!newClass) return;
Method method = class_getInstanceMethod([_SwizzleHelper class], @selector(canPerformAction:));
class_addMethod(newClass, @selector(canPerformAction:), method_getImplementation(method), method_getTypeEncoding(method));
objc_registerClassPair(newClass);
}
object_setClass(subview, newClass);
}
这篇关于UIWebView:禁用富文本编辑器的复制/剪切选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!