[英]Opening ViewController programmatically
我在同一故事板上有另一個ViewController,我想通過單擊一個按鈕切換到該故事板上。 問題是當我嘗試按住Control並拖動第二個視圖控制器以在主viewcontroller的ViewController.m文件內創建一個Outlet時,沒有創建一個Outlet。
在Android中,我們可以從另一個活動中打開具有不同UI的新活動 。 我確定同樣可以在iOS中實現,所以我的問題是如何創建第二個View Controller的出口並以編程方式打開它 ?
使用Storyboard Identifier
可以以編程方式打開SecondViewController
,您需要為要切換到的類提供Storyboard標識符名稱,請參見此圖像 ,在我的演示中,我使用了secondViewController
現在,在您的buttonClick事件方法中使用此代碼。
- (IBAction)buttonClicked:(id)sender {
UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
SecondViewController *secondViewController = (SecondViewController *)[mainStoryboard instantiateViewControllerWithIdentifier:@"secondViewController"];
// Use this to show your UIViewController in modal transition.
[self presentViewController:secondViewController animated:YES completion:nil];
// Use this to show your UIViewController in push transition with navigation controller
//[self.navigationController pushViewController:secondViewController animated:YES];
}
Try this
Viewcontroller*homeVC;
[self.navigationController setNavigationBarHidden:YES];
UIStoryboard *storyBoard;
storyBoard=[UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
homeVC=(HomeVC*)[storyBoard instantiateViewControllerWithIdentifier:@"HomeVC"];
[self.navigationController pushViewController:homeVC animated:YES];
正如其他人所提到的,您不能這樣做。 要覆蓋並啟動VC並保留其屬性,您可以:
首先,在viewControllers之間創建segue:雙擊界面生成器的背景來縮小視圖。 按住Ctrl鍵並從一個VC拖動到另一個VC,然后選擇segue的類型(例如show)。
比為按鈕創建操作,您可以:
[self performSegueWithIdentifier:@"myIdentifier" sender:self];
之后,在-(void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
檢查標識符中,設置新的yourCustomClassViewController並瞧瞧!
if ([segue.identifier isEqualToString:@"myIdentifier"]) {
myCustomClassViewController *myCustomVC = [segue destinationViewController];
myCustomVC.oldProfile = newProfile;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.