您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

Objective-C 視圖跳轉實作:從 RootViewController 推入新頁面

編輯:iOS 開發綜合

記錄一下在 iPhone 上做頁面跳轉的完整流程,以「訂單列表」按下新增按鈕後推入「新增訂單」頁面為例。

步驟一:建立新的 view controller

新增 NewOrderViewController,讓 Xcode 一併產生 .h 與 .m 檔。

步驟二:建立對應的 view

新增 NewOrderView.xib。雙擊開啟後,把它的 class 指定為 NewOrderViewController,並在 Interface Builder 中把 view 與 File Owner 連接起來,否則執行時會拿到空白畫面。

步驟三:在 RootViewController.h 宣告屬性

@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 裡,否則畫面不會動。
  • 在 MRC 語境下,先賦值給 retain 屬性再 release 區域變數是標準寫法,避免多餘的一份所有權。
  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved