177

在我的应用程序中,我有一个以编程方式执行 segue 的按钮:

- (void)myButtonMethod
{
    //execute segue programmatically
    [self performSegueWithIdentifier: @"MySegue" sender: self];
}

我想知道是否有办法引用目标视图并传递一些参数。

我知道在prepareForSegue方法中,我可以用: 来引用它myDestinationViewController *vc = [segue destinationViewController];,但我不知道如何以编程方式执行 segue。

你有什么想法?

谢谢,亚萨


更新:

对不起这个问题!!!我只是发现,即使以编程prepareForSegue方式调用 segue,无论如何都会调用该方法,因此可以以相同的方式传递参数。

4

5 回答 5

108

答案很简单,segue 的触发方式没有区别。

在任何情况下都会调用该prepareForSegue:sender:方法,这是您传递参数的地方。

于 2012-05-28T10:22:14.770 回答
91

老问题,但这里是关于如何做你所问的代码。在这种情况下,我将数据从表格视图中的选定单元格传递到另一个视图控制器。

在 trget 视图的 .h 文件中:

@property(weak, nonatomic)  NSObject* dataModel;

在 .m 文件中:

@synthesize dataModel;

dataModel可以是string,int或 like 在这种情况下它是一个包含许多项目的模型

- (void)someMethod {
     [self performSegueWithIdentifier:@"loginMainSegue" sender:self];
 }

或者...

- (void)someMethod {
    UIViewController *myController = [self.storyboard instantiateViewControllerWithIdentifier:@"HomeController"];
    [self.navigationController pushViewController: myController animated:YES];
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if([segue.identifier isEqualToString:@"storyDetailsSegway"]) {
        UITableViewCell *cell = (UITableViewCell *) sender;
        NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
        NSDictionary *storiesDict =[topStories objectAtIndex:[indexPath row]];
        StoryModel *storyModel = [[StoryModel alloc] init];
        storyModel = storiesDict;
        StoryDetails *controller = (StoryDetails *)segue.destinationViewController;
        controller.dataModel= storyModel;
    }
}
于 2012-12-20T21:11:56.740 回答
3

斯威夫特 4:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "ExampleSegueIdentifier" {
        if let destinationVC = segue.destination as? ExampleSegueVC {
            destinationVC.exampleString = "Example"
        }
    }
}

斯威夫特 3:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if segue.identifier == "ExampleSegueIdentifier" {
            if let destinationVC = segue.destinationViewController as? ExampleSegueVC {
                destinationVC.exampleString = "Example"
            }
        }
    }
于 2018-03-12T10:06:24.587 回答
0

我理解在一个地方执行 segue 并保持状态以发送参数以准备 segue 的问题。

我想出了一个办法来做到这一点。我使用类别向 ViewControllers 添加了一个名为 userInfoDict 的属性。而且我也用标识符覆盖了执行segue,这样如果发件人是自己的(意味着控制器本身)。它将这个 userInfoDict 传递给下一个 ViewController。

在这里,除了传递整个 UserInfoDict 之外,您还可以传递特定的参数,作为发送者并相应地覆盖。

1件事你需要记住。不要忘记在您的 performSegue 方法中调用超级方法。

于 2013-09-05T20:57:28.420 回答
0

如果您使用新的 swift 版本。

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "ChannelMoreSegue" {

        }
}
于 2018-03-08T10:53:29.447 回答