記錄一下在 iPhone 上做頁面跳轉的完整流程,以「訂單列表」按下新增按鈕後推入「新增訂單」頁面為例。
新增 NewOrderViewController,讓 Xcode 一併產生 .h 與 .m 檔。
新增 NewOrderView.xib。雙擊開啟後,把它的 class 指定為 NewOrderViewController,並在 Interface Builder 中把 view 與 File Owner 連接起來,否則執行時會拿到空白畫面。
@class NewOrderViewController;
@interface RootViewController : UITableViewController {
NewOrderViewController *newOrderViewController;
}
@property (nonatomic, retain) NewOrderViewController *newOrderViewController;
@end
先在 viewDidLoad 裡加上導覽列標題與左右兩顆按鈕:
- (void)viewDidLoad {
[super viewDidLoad];
self.navigationItem.title = @"訂單列表";
self.navigationController.navigationBar.barStyle = UIBarStyleBlack;
UIBarButtonItem *buttonEdit = [[[UIBarButtonItem alloc]
initWithTitle:@"編輯" style:UIBarButtonItemStyleBordered
target:self action:@selector(editCharacters)] autorelease];
UIBarButtonItem *buttonAdd = [[[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemAdd
target:self action:@selector(showNewOrderView)] autorelease];
self.navigationItem.leftBarButtonItem = buttonEdit;
self.navigationItem.rightBarButtonItem = buttonAdd;
}
接著實作推頁面的方法。這裡刻意做了「遅刭建立」處理:只有在第一次按下新增鈕時才真正建立 view controller,之後重複使用同一個實例,省下不必要的物件配置。
- (void)showNewOrderView {
if (self.newOrderViewController == nil) {
NewOrderViewController *newOrder =
[[NewOrderViewController alloc] initWithNibName:@"NewOrderView" bundle:nil];
self.newOrderViewController = newOrder;
[newOrder release];
}
[self.navigationController pushViewController:self.newOrderViewController animated:YES];
}
initWithNibName: 的字串必須與 xib 檔名一致(不含副檔名),否則會出現找不到 nib 的錯誤。pushViewController:animated: 需要 naviagation controller 存在,也就是 RootViewController 必須被包在 UINavigationController 裡,否則畫面不會動。release 區域變數是標準寫法,避免多餘的一份所有權。