Different URIs for each instance of the UIViewController

I have a UITabController with five tabs. Each tab simply contains an instance of a custom UIViewController, and each instance contains a UIWebView.

I want the UIWebView on each tab to open a different URI, but I don't think it should be necessary to create a new class for each tab.

I can make it work if I do [self.webView loadRequest:]in -(void)viewDidLoad, but it seems ridiculous to create five different classes with five different versions of viewDidLoad when all I really want to change is a URI.

Here is what I tried:

appDelegate.h

#import <UIKit/UIKit.h>

@interface elfAppDelegate : UIResponder <UIApplicationDelegate, UITabBarControllerDelegate>

@property (strong, nonatomic) UIWindow *window;
@property (strong, nonatomic) UITabBarController *tabBarController;

@end

appDelegate.m

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

    customVC *start = [[customVC alloc] init];
    customVC *eshop = [[customVC alloc] init];
    customVC *table = [[customVC alloc] init];
    customVC *video = [[customVC alloc] init];
    customVC *other = [[customVC alloc] init];

    // Doesn't do anything... I wish it would!
    [start.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://google.com"]]];

    self.tabBarController = [[UITabBarController alloc] init];
    self.tabBarController.viewControllers = @[start, eshop, table, video, other];

    self.window.rootViewController = self.tabBarController;
    [self.window makeKeyAndVisible];
    return YES;
}

customVC.h

#import <UIKit/UIKit.h>

@interface customVC : UIViewController <UIWebViewDelegate> {
    UIWebView* mWebView;
}

@property (nonatomic, retain) UIWebView* webView;

- (void)updateAddress:(NSURLRequest*)request;
- (void)loadAddress:(id)sender event:(UIEvent*)event;

@end

customVC.m

@interface elfVC ()

@end

@implementation elfVC

@synthesize webView = mWebView;

- (void)viewDidLoad {
    [super viewDidLoad];

    self.webView = [[UIWebView alloc] init];
    [self.webView setFrame:CGRectMake(0, 0, 320, 480)];
    self.webView.delegate = self;
    self.webView.scalesPageToFit = YES;

    [self.view addSubview:self.webView];

}
+5
source share
2 answers

NSURL* customVC.

customVC -(id)init -(id)initWithURL:(NSURL*)url :

-(id)initWithURL:(NSURL*)url{
 self = [super init];
 if(self){ 
  self.<URLPropertyName> = url;
 }
 return self;
}

[start.webView loadRequest:[NSURLRequest requestWithURL:self.<URLPropertyName>]];

in viewDidLoad

, customVC,

customVC *vc = [customVC alloc]initWithURL:[NSURL URLWithString:@"http://..."]];
+3

, - loadRequest:. , , :

- (UIWebView*)webview {
    if (mWebView == nil) {
        // do the initialization here
    }
    return mWebView;
}

, - ( loadRequest:), , viewDidLoad.

+1

All Articles