[英]iOS: present view controller programmatically
我正在使用presentViewController:animated:completion:
方法轉到另一個視圖控制器。
這是我的代碼:
AddTaskViewController *add = [[AddTaskViewController alloc] init];
[self presentViewController:add animated:YES completion:nil];
此代碼轉到另一個UIViewController
但另一個控制器為空。 我一直在使用情節提要,但現在我需要用代碼來完成。
如果您使用的是故事板,則可能不應該使用alloc
和init
來創建新的視圖控制器。 相反,請查看您的情節提要 ,找到要執行的片段 ; 它應具有唯一的標識符(如果沒有,則可以在右側欄中設置一個)。
找到該segue的標識符后,向您當前的視圖控制器-performSegueWithIdentifier:sender
消息:
[self performSegueWithIdentifier:@"mySegueIdentifier" sender:self];
這將使情節提要板實例化一個AddTaskViewController並以您為該腳本定義的方式呈現它。
另一方面,如果您根本不使用情節提要,那么您需要為AddTaskViewController提供某種用戶界面。 最常見的方法是使用nib初始化控制器:您將調用-initWithNibName:bundle:
而不是僅調用init
,並提供包含添加任務UI的.xib文件的名稱:
AddTaskViewController *add = [[AddTaskViewController alloc]
initWithNibName:@"AddTaskView" bundle:nil];
[self presentViewController:add animated:YES completion:nil];
(還有其他(較不常見)的方法來獲取與新視圖控制器相關聯的視圖,但這可能為您帶來最少的工作上的麻煩。)
如果您使用的是Storyboard,而“ add” viewController在Storyboard中,請在設置中為您的“ add” viewcontroller設置一個標識符,以便您可以執行以下操作:
UIStoryboard* storyboard = [UIStoryboard storyboardWithName:@"NameOfYourStoryBoard"
bundle:nil];
AddTaskViewController *add =
[storyboard instantiateViewControllerWithIdentifier:@"viewControllerIdentifier"];
[self presentViewController:add
animated:YES
completion:nil];
如果在情節提要或nib文件中沒有“添加” viewController,並且想以編程方式創建整個內容,則appDocs會說:
如果您無法在情節提要或Nib文件中定義視圖,請重寫loadView方法以手動實例化視圖層次結構並將其分配給view屬性。
您需要通過情節提要身份檢查器設置情節提要ID
AddTaskViewController *add=[self.storyboard instantiateViewControllerWithIdentifier:@"storyboard_id"];
[self presentViewController:add animated:YES completion:nil];
您的代碼:
AddTaskViewController *add = [[AddTaskViewController alloc] init];
[self presentViewController:add animated:YES completion:nil];
這段代碼可以轉到另一個控制器,但是您會得到一個新的viewController,而不是情節提要的控制器,您可以這樣操作:
AddTaskViewController *add = [self.storyboard instantiateViewControllerWithIdentifier:@"YourStoryboardID"];
[self presentViewController:add animated:YES completion:nil];
最好的方法是
AddTaskViewController * add = [self.storyboard instantiateViewControllerWithIdentifier:@"addID"];
[self presentViewController:add animated:YES completion:nil];
您可以在Swift中執行以下操作:
let vc = UIViewController()
self.presentViewController(vc, animated: true, completion: nil)
請嘗試以下操作:
NextViewController *nextView = [self.storyboard instantiateViewControllerWithIdentifier:@"nextView"];
[self presentViewController:nextView animated:YES completion:NULL];
試試這個代碼:
[self.navigationController presentViewController:controller animated:YES completion:nil];
LandingScreenViewController *nextView=[self.storyboard instantiateViewControllerWithIdentifier:@"nextView"];
[self presentViewController:nextView animated:YES completion:^{}];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.