0

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!

Dmitry
  • 14,306
  • 23
  • 105
  • 189

1 Answers1

0

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...

jjv360
  • 4,120
  • 3
  • 23
  • 37
  • Replaced method works perfectly but nasty items on a popup menu of `UIWebView` still exist :(( http://stackoverflow.com/questions/13233613/how-to-disable-popup-menu-items-like-select-select-all-suggest-define-on – Dmitry Nov 05 '12 at 14:49
  • It sounds strange but if you call your function inside your function it'll actually call the replaced one... – jjv360 Nov 06 '12 at 06:24
  • Method A was replaced by method B. Now I want to call A inside B. How to do it? – Dmitry Nov 06 '12 at 10:09
  • `-(void) B { [self B]; }` It looks like it'll cause a loop but when you call B from inside B it actually calls A. – jjv360 Nov 06 '12 at 11:52
  • But do you know how to fix it? – Dmitry Nov 06 '12 at 15:09