我有一个带有 contentEditable div 的 UIWebView 来实现某种富文本编辑器。一旦用户选择任何文本片段,我需要修剪 UIMenuController 中出现在 Web 视图中的复制和剪切选项。
网络上似乎有很多解决方案,但由于某种原因,没有一个适用于我的场景。
我已经对 UIWebView 进行了子类化并实现了canPerformAction:(SEL)action withSender:
删除复制和剪切,但是一旦用户选择“选择”或“全选”,就会出现一个新菜单,显然,Web 视图不会拦截此操作,并且不会调用 canPerform 方法。
有没有办法减少这种情况下的操作?
我会适应我的另一个答案 https://stackoverflow.com/a/19042279/983912对于你的情况。
The canPerformAction:
实际上是在内部调用的UIWebDocumentView
而不是UIWebView
,您通常不能对其进行子类化。借助一些运行时魔法,这是可能的。
我们创建一个具有一个方法的类:
@interface _SwizzleHelper : UIView @end
@implementation _SwizzleHelper
-(BOOL)canPerformAction:(SEL)action
{
//Your logic here
return NO;
}
@end
一旦您拥有想要控制其操作的 Web 视图,您就可以迭代其滚动视图的子视图并获取UIWebDocumentView
班级。然后,我们动态地将上面创建的类的超类设为子视图的类(UIWebDocumentView - 但我们不能预先这么说,因为这是私有 API),并将子视图的类替换为我们的类。
#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);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)