Change the class of a widget on a xib? (Change a UIWebView to my own Category of UIWebView)

155 views Asked by At

I have a working .xib in Xcode 5. The main widget is a UIWebView. The widget has its position, connections, and outlets all correctly arranged.

Later I created a Category of UIWebView (UIWebView+ReadOnlyPageContent) to override the canPerformAction:withSender: method.

➥ Is there a way to reassign the class of the widget to the category?

In Xcode's Identity inspector > Custom Class > Class field, I see "UIWebView". But the text is greyed out and only "UIWebView" is listed in the popup menu.

Screen shot of Xcode's Identity inspector > Custom Class > Class field

In my view controller I tried redefining the UIWebView widget, going from this:

 IBOutlet UIWebView *webView; // Works.

to my category, with an #import of the category:

 IBOutlet UIWebView+ReadOnlyPageContent *webView; // Fails. 3 compiler errors. 

As an alternative I had considered making a subclass of UIWebView. But the documentation says UIWebView should not be subclassed. So the use of a category is the only way I can think to override the canPerformAction:withSender: method.

- (BOOL)canPerformAction:(SEL)action
              withSender:(id)sender
{
    if (
        action == @selector(select:) ||
        action == @selector(copy:) ||
        action == @selector(cut:) ||
        action == @selector(paste:)
        )
    {
        return NO;
    }
    return [super canPerformAction:action withSender:sender];
}
1

There are 1 answers

3
Axeva On

A category on the UIWebView class is not going to appear in Xcode like that. If you had created a sub-class of UIWebView it would appear there, but a Category is just an extension of the existing UIWebView class.

The larger question is: What are you doing in the Category that you need access to in Xcode?

Update:

Using a category to override an existing class method is not encouraged by Apple. See this Stack Overflow response for details: Overriding methods using categories in Objective-C

Here is the key phrase:

Although the Objective-C language currently allows you to use a category to override methods the class inherits, or even methods declared in the class interface, you are strongly discouraged from doing so. A category is not a substitute for a subclass.

If the goal is simply to disable copy and paste in the web view, it may be easier to just inject some CSS into the HTML, such as:

<style>
* {
  -webkit-touch-callout: none;
  -webkit-user-select: none;
}
</style>