首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

iOS 模態視圖控制器跳轉:正確關閉返回根視圖

     編輯:程式設計綜合問答

場景

根視圖 ViewController 以 presentViewController 彈出 EventViewController,在後者中需返回根視圖。

錯誤嘗試

// 在 EventViewController 中
self.vc = [[ViewController alloc] init]; // 重新建立實例!錯誤
[self presentViewController:self.vc animated:YES completion:nil]; // 再彈一層

正確做法:dismiss 當前模態視圖

// 在 EventViewController 的按鈕動作中
- (IBAction)iconAction {
    [self dismissViewControllerAnimated:YES completion:nil];
}

原理

  • presentViewController 建立模態堆疊
  • 返回上一層只需 關閉當前頂層模態視圖,系統自動顯示下層
  • 切勿 new 根視圖控制器,那會建立新實例導致狀態丟失

傳遞資料回根視圖

使用 Delegate 代理模式 或 Block 回調:

// EventViewController.h
@property (weak) id delegate;

// 關閉前
[self.delegate eventDidFinishWithData:data];
[self dismissViewControllerAnimated:YES completion:nil];
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved