Search code examples
iphoneiosipaduiwebviewsubclassing

How to replace method of UIWebView instead restricted subclassing?


Subclassing of UIWebView is restricted by Apple. But I need to replace method canPerformAction to the following one:

-(BOOL) canPerformAction:(SEL)action withSender:(id)sender {
    if ((action == @selector(Copy:)) || (action == @selector(Paste:))) {
        return YES;
    } else {
        return NO;
    }
}

How to replace this method without subclassing? Thank you a lot for the help!


Solution

  • To replace a function in a class you can use method swizzling. There's a nice library that does everything for you called JRSwizzle.

    [[UIWebView class] jr_swizzleMethod:@selector(canPerformAction:withSender:) withMethod:@selector(myCanPerformAction:withSender:) error:nil];
    

    The all you need to do is to create a category on UIWebView that implements myCanPerformAction:withSender:

    -(BOOL) myCanPerformAction:(SEL)action withSender:(id)sender {
        if ((action == @selector(Copy:)) || (action == @selector(Paste:))) {
            return YES;
        } else {
            return NO;
        }
    }
    

    Not sure if this is good practice though...