Setting a UIWebViewDelegate programmatically
-
19-09-2019 - |
Question
I am trying to build a custom control based on a UIWebView and compile it into a library for reuse. Everything was working just fine when I had the code all together in a single test app but I'm having some trouble setting up a the delegate for the view for a library. Of note, the sample app used interface builder and thus the delegate was set via IB.
NewsView.h:
@interface NewsView : UIWebView {
NSObject<UIWebViewDelegate> *delegate;
}
@property (nonatomic, assign) IBOutlet NSObject<UIWebViewDelegate> *delegate;
In the implementation all of my initialization methods call a common method viewInit
NewsView.m
@implementation NewsView
@synthesize delegate;
- (void)viewInit {
self.delegate = [[NewsViewDelegate alloc] init];
}
If the user clicks on one of the headlines in the view I need the delegate to intercept clicks and launch Safari.
NewsViewDelegate.h
@interface NewsViewDelegate : NSObject <UIWebViewDelegate> {
}
NewsViewDelegate.m
// Intercept URL events
- (BOOL)webView:(UIWebView *)myWebView shouldStartLoadWithRequest:
(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
NSLog(@"URL Changed");
// Check to see if this is a click event
if (navigationType == UIWebViewNavigationTypeLinkClicked) {
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:[[request URL] absoluteString]]];
return NO;
}
return YES;
}
Unfortunately shouldStartLoadWithRequest never gets called and so clicks are not being launched externally.
Solution
It's typically a bad idea to subclass UIWebView
, and the docs specifically advise against it. I don't know for sure, but my guess is that UIWebView
is a class cluster.
To get the effect you want, you might try making your NewsView a plain UIView
, then add the UIWebView
as a subview. From there you can set the UIWebView delegate to the NewsViewDelegate without worrying about the subclass.
The best method might be to create a NewsViewController class that loads your NewsView and implements the UIWebViewDelegate
methods itself and set the NewsView webView delegate to your NewsViewController.
OTHER TIPS
You are shadowing the existing delegate
property of the webview. Try to simply not include the delegate
property in your subclass. It should be inherited.