編寫簡單的導航控制器

來源:互聯網
上載者:User

導航控制器(UINavigationController)是iOS介面中重要的組成部分。一般來說導航控制器要結合TableView來使用,因此我在摸導航控制器前先寫了簡單的TableView(編寫簡單的TableView),下面的例子也是在這個例子基礎上寫的。

本文是參考《iPhone開發基礎教程》寫的,但是這部分教程太囉嗦了。我做了精簡,並拆分成幾個漸進的小例子。第一個例子:

首先,要建立Navigation-based Application:

這樣,xcode會幫你產生一個導航項目的架構。xcode產生的RootViewController實際上是一個UITableViewController,這和編寫簡單的TableView是很類似的。

可以在IB中找到MainWindow.xib,為導航首頁增加標題:

然後,和TableView類似,編寫dataSource,不過不需要通過IB做關聯到file’s owner了。只需要在RootViewController中“填空”即可,標頭檔中:

@interface RootViewController : UITableViewController <UITableViewDelegate,UITableViewDataSource>{
    NSArray *dataItems;

在m檔案:

@synthesize dataItems;

- (void)viewDidLoad {
    [super viewDidLoad];

    dataItems= [[NSArray alloc] initWithObjects:@"張三",@"李四",nil];
    [super viewDidLoad];
}

// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [dataItems count];
}

另外,為了做出這個如下的效果:

需要再增加一個函數:

-(UITableViewCellAccessoryType)tableView:(UITableView *)tableView accessoryTypeForRowWithIndexPath:(NSIndexPath *)indexPath{
    return UITableViewCellAccessoryDetailDisclosureButton;
}

這時還沒有牽扯到導航控制器的主要內容,只是做了個TableView而已。

建立詳細內容的控制器,DetailViewController以及對應的xib檔案。需要注意的是要在IB中做控制器到視圖之間的關聯工作。

然後,將DetailViewController設定為RootViewController的成員:

@interface RootViewController : UITableViewController <UITableViewDelegate,UITableViewDataSource>{
    NSArray *dataItems;
    DetailViewController *detailViewController;
}

之後,回到RootViewController.m檔案中,增加用於處理列表按鈕的函數:

-(void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath{
    if (detailViewController==nil) {
        detailViewController=[[DetailViewController alloc] initWithNibName:@"DetailView" bundle:nil];
    }
    detailViewController.title=@"Detail";
    NavTestAppDelegate *delegate=[[UIApplication sharedApplication] delegate];
    [delegate.navigationController pushViewController:detailViewController animated:YES];
}

 

在該函數中初始化了DetailViewController,並且將這個控制器壓棧到控制器棧中。運行程式,就是上面的效果。

這裡要注意,本例中選中條目並不會到詳細頁面,而必須點擊表徵圖按鈕才行。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.