UINavigationController

导航控制器UINavigationController控制一系列的UIViewController,他们组成一个层次结构,每一个ViewController都在这个层次结构中上下移动,组织方式是栈形式。

每个UIViewController都有相关联的UINavigationItem,后者处于活动状态时将位于UINavigationBar中,每个UINavigationItem都可能包含一个或多个UIBarButtonItem,让导航栏能包括其他操作项。

一般情况下,导航控制器结构包含四个对象:

一个UINavigationController;

一个UINavigationBar;

一个UIViewController;

一个UINavigationItem(放在UINavigationBar中)

下面来创建一个导航控制器:

首先建立一个Empty project,在AppDelegate.h中声明并在m文件中实现:

@property (strong,nonatomic)UINavigationController *navController;

 

然后建一个RootViewController继承UITableViewController作为导航控制器的根视图

 

然后建立MovieViewController来作为RootViewController条目的子视图

 

在RootViewController里面添加方法:

(void)viewDidLoad  
{  
    [superviewDidLoad];  
    self.title = @"类别";  
    NSMutableArray *array = [[NSMutableArrayalloc]init];  
      
    MovieController *movieController = [[MovieControlleralloc]initWithStyle:UITableViewStylePlain];  
    movieController.title = @"电影";  
    [array addObject:movieController];  
      
    self.controllerList = array;  

 由于继承了UITableViewController,所以要实现必要的方法,这里列出关键代码:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath  
{  
    staticNSString *CellIdentifier = @"Cell";  
      
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];  
    if (cell == nil) {  
        cell = [[[UITableViewCellalloc] initWithStyle:UITableViewCellStyleDefaultreuseIdentifier:CellIdentifier] autorelease];  
    }  
      
    // Configure the cell...  
    NSUInteger row = [indexPath row];  
    UITableViewController *controller = [self.controllerListobjectAtIndex:row];  
    cell.textLabel.text = controller.title;  
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;  
      
    return cell;  
}  

 这是单击条目后进入子视图的方法:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath  
{  
    NSUInteger row = [indexPath row];  
    UITableViewController *detailController = [self.controllerListobjectAtIndex:row];  
     //进入下一个视图的操作  
    [self.navigationControllerpushViewController:detailController animated:YES];  
    [detailController release];  

 这样基本实现了导航控制的目的,导航栏上方的返回按钮是根据前一个视图的标题自动生成的。

另外还有一些操作是为导航栏添加左右按钮,

self.navigationItem.rightBarButtonItem = [UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItem addTarget:self : action:@selector(change)];

定义顶部左右按钮的方式有如下几种:

initWithBarButtonSystem:target:action: :创建一个标准按钮

initWithCustomView: 自定义按钮(view)

initWithImage:style:target:action 创建一个带图片的按钮

initWithTitle:style:target:action 创建一个带标题的按钮

猜你喜欢

转载自1395014506.iteye.com/blog/2246628