UIViewController的每个实例的不同URI

时间:2013-03-20 13:29:15

标签: ios objective-c

我有一个带有五个标签的UITabController。每个选项卡只包含一个自定义UIViewController的实例,每个实例都包含一个UIWebView。

我希望每个标签中的UIWebView打开不同的URI,但我认为不必为每个标签创建一个新类。

如果我在[self.webView loadRequest:]-(void)viewDidLoad,我可以使它工作但是当我真正想要改变的是URI时,用五个不同版本的viewDidLoad创建五个不同的类似乎很荒谬。

这是我尝试过的:

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];

}

2 个答案:

答案 0 :(得分:3)

在customVC中创建NSURL*类型的属性。

将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>]];
viewDidLoad

中的

然后,当您初始化customVC的不同实例时,只需使用

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

答案 1 :(得分:1)

我怀疑你在调用它的loadRequest:方法之后正在初始化你的webview。为避免这种情况,最好通过覆盖其setter来初始化非原子属性:

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

通过这种方式,您首次访问它时(在调用loadRequest:时),而不是在自定义视图控制器的viewDidLoad方法之后,您的网页视图将被初始化。