簡體   English   中英

以編程方式打開ViewController

[英]Opening ViewController programmatically

我在同一故事板上有另一個ViewController,我想通過單擊一個按鈕切換到該故事板上。 問題是當我嘗試按住Control並拖動第二個視圖控制器以在主viewcontroller的ViewController.m文件內創建一個Outlet時,沒有創建一個Outlet。

在Android中,我們可以從另一個活動中打開具有不同UI的新活動 我確定同樣可以在iOS中實現,所以我的問題是如何創建第二個View Controller的出口並以編程方式打開它

在iOS中無法從一個ViewController到另一個ViewController創建IBOutlet ,但是您可以為此使用UIStoryboardSegue

我建議您遵循“ 教程: Apple文檔中的故事板 ”。 它將幫助您了解ViewControllers是如何實際連接的。

使用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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM