xcode4.2 中tabBar的模板的一些理解和体会

来源:互联网 发布:vmware linux上网设置 编辑:程序博客网 时间:2024/05/02 21:03

在xcode4.2中提供了一个 Tabbed Application模板,用于建立一个具有2个按钮的控制栏的应用。

他的实现方法和《iphone 开发应用程序指南》一书上的思路不一致。主要的实现,是通过以下几点来完成的。

1。不构建rootViewController这个控制器。而是通过编程方法来实现。主要代码在AppDelegate.m文件中的didFinishLaunchingWithOptions体现

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];    // Override point for customization after application launch.    UIViewController *viewController1 = [[NewsViewController alloc] initWithNibName:@"NewsViewController" bundle:nil];    UIViewController *viewController2 = [[RecommendViewController alloc] initWithNibName:@"RecommendViewController" bundle:nil];    UIViewController *viewController3 = [[AboutViewController alloc] initWithNibName:@"AboutViewController" bundle:nil];        self.tabBarController = [[UITabBarController alloc] init];    self.tabBarController.viewControllers = [NSArray arrayWithObjects:viewController1, viewController2, viewController3,nil];    self.window.rootViewController = self.tabBarController;    //注意这段代码,只有设置了tabBarController的委托才能激活次.m文件中didSelectViewController方法    self.tabBarController.delegate = self;          [self.window makeKeyAndVisible];    return YES;}

2。核心关键代码解释:

2.1 代码:

   UIViewController *viewController1 = [[NewsViewController alloc] initWithNibName:@"NewsViewController" bundle:nil];

主要目的是通过nib的名称来构建一个 ViewController。这样的好处在于:可以通过松耦合的形式,把要显示的视图完全独立出来。这个视图可以有自己的Controller和xib文件来控制。比如,这个NewsViewController,就是由NewsViewController.h , NewsViewController.m 和 NewsViewController.xib3个文件构成一个独立的组件

2。2 代码

    self.tabBarController = [[UITabBarController alloc] init];    self.tabBarController.viewControllers = [NSArray arrayWithObjects:viewController1, viewController2, viewController3,nil];

就是通过由三个视图组件构成的数组来初始化这个TabBar,使其拥有3个按钮选项。

2。3代码

  self.window.rootViewController = self.tabBarController;

由于AppDelegate没有相应的界面,通过以上代码,就直接把 tabBarController设置成主程序的rootViewController。这样就可以在主界面显示出这个控制条和对于的视图了。

2。4代码

self.tabBarController.delegate = self;  

通过把tabBarController的委托指向appDelegate,就可以使得我们切入tabBar的事件中去,进行编程。

3。切入tabBarController的动作中,进行个性化编程。

     由于2。4代码的存在。所以我们可以放开appDelegate.m文件中原来注释掉的方法。

// Optional UITabBarControllerDelegate method.- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController{    NSLog(@"11111111");}

  这样我们在点击tabBar的每个按钮时候都会打印出1111111字符串。说明切入成功。


一些体会:

  个人认为:通过这种方法来处理TabBar,使得程序各个组件松耦合。结构清晰。代码简单。


原创粉丝点击