How to show SomeViewControler using code?

2019-09-17 02:15发布

I am brand new in Xcode and iOS development. I am trying to figure out how to open/show some view based on button click. I know that I can do this using ctrl + mouse click on some ViewController using segue but I need to add some logic before. How can I accomplish this?

2条回答
霸刀☆藐视天下
2楼-- · 2019-09-17 02:25
Anthone
3楼-- · 2019-09-17 02:36

There are two ways to make segues work.

You can either ctrl drag from a button to a new ViewController (like you have done) or you can ctrl drag from one ViewController to a new ViewController (drag from the little orange square icon in the bar underneath the VC).

For both ways you can set an identifier on the segue that gets created. This is used to refer to it in the code.

When you do the first way you are saying "When this button is pressed, move to this ViewController". This means that whenever that button is pressed it will move to the new VC.

The second way just tells the storyboard that there will be a segue to move to the new VC. To run it you would then add a IBAction to your button (instead of the segue).

In the action for the button you then have...

- (IBAction)buttonPressed:(id)sender
{
    if (someConditionToCheckMoveToNewVC)
    {
        [self performSegueWithIdentifier:@"mySegue" sender:nil];
    }
}

This will then only perform that segue if the condition you have checked is true.

You can also pass information to the new VC like so...

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    NewViewController *nvc = segue.destinationViewController;

    nvc.someProperty = @"blah";
}

this will then set the property in the new VC before transitioning to it.

查看更多
登录 后发表回答