pushを実現する最も簡単なサンプル。
「新規プロジェクト」で「Navigation-based Application」を選択。
プロジェクト名は、とりあえず「NavTest」として保存。
以下の4つのclassが生成される。
NavTestAppDelegate.h
NavTestAppDelegate.m
RootViewController.h
RootViewController.m
次にpushされるViewControllerを生成する。
「classes」フォルダを選択し、右クリックから「追加」>「新規ファイル」。
「cocoa touch Class」の「UIViewControllerSubclass」を選択。
ファイル名はとりあえず「DtailViewController」とする。
以下の2つのクラスが「classes」に追加される。
DetailViewController.h
DetailViewController.m
RootViewControllerクラスに以下のコードを記述。
NavTestAppDelegateクラスとDetailViewControlllerクラスは特に変更しない。
RootViewController.h
#import <UIKit/UIKit.h>
//※子となるViewControllerクラスのヘッダーファイルをインポート
#import "DetailViewController.h"
@interface RootViewController : UITableViewController {
NSArray *items;
//※子となるViewControllerクラスのインスタンスを宣言
DetailViewController *detailViewController;
}
@end
RootViewController.m
#import "RootViewController.h"
@implementation RootViewController
#pragma mark -
#pragma mark View lifecycle
- (void)viewDidLoad {
[super viewDidLoad];
self.title=@"ayabin";
items=[[NSArray arrayWithObjects:@"test1",@"test2",@"test3",nil] retain];
//※「retain」しないと、この「viewDidLoad」メソッドのみでしか、itemsを保持できない。つまり他のメソッドでは再定義が必要になる
}
#pragma mark -
#pragma mark Table view data source
// Customize the number of sections in the table view.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [items count];
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
// Configure the cell.
cell.textLabel.text=[items objectAtIndex:indexPath.row];
return cell;
}
#pragma mark -
#pragma mark Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
//※子となるViewControllerクラスのインスタンスを初期化
detailViewController=[[DetailViewController alloc] initWithNibName:@"DetailViewController" bundle:nil];
//※子となるViewControllerクラスに情報をセット
detailViewController.title=[items objectAtIndex:indexPath.row];
//※子となるViewControllerクラスのインスタンスをnavigationControllerにセット
[self.navigationController pushViewController:detailViewController animated:YES];
//※子となるViewControllerクラスを解放
[detailViewController release];
}
- (void)dealloc {
[super dealloc];
[items release];
}
@end
コメントする