【问题标题】:Detect which button was pressed to open this view [duplicate]检测按下哪个按钮来打开此视图[重复]
【发布时间】:2013-01-26 21:51:34
【问题描述】:

可能重复:
Passing variables between view controllers

假设我在同一个 ViewController(FirstController) 中有 3 个按钮,标签为 1-3。所有三个按钮都打开了一个新的ViewController(SecondController)。但是我如何才能在SecondController 中检查按下了什么按钮才能到达这里,或者使用了什么segue?因此SecondController 可以根据按下哪个按钮打开它来执行不同的操作。我可能在考虑开关和外壳。

【问题讨论】:

  • 如何将点击的按钮标签存储在共享变量中或使用通知?
  • 我今天早些时候回答了您的类似问题,并向您展示了如何做到这一点。你不明白吗?

标签: ios cocoa


【解决方案1】:

有两种可能的方法。

一种方法是为每个按钮分配一个唯一的转场。在prepareForSegue: 方法上,您识别按钮并将该信息提供给destinationViewController:

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([segue.identifier isEqualToString:@"Button1Segue"]) {
        [segue.destinationViewController setButton:1];
    }

    if ([segue.identifier isEqualToString:@"Button2Segue"]) {
    ...
}

另一种方法是创建一个 property 来存储最后按下的按钮。

- (IBAction)buttonTap:(id)sender {

    self.lastPressedButton = sender.tag;
}

在prepareForSegue: 你会这样做:

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([segue.identifier isEqualToString:@"SecondControllerSegue"]) {
        [segue.destinationViewController setButton: self.lastPressedButton];
    }
}

希望对你有帮助

【讨论】:

    【解决方案2】:
    if (button.tag == 0) {
       NSLog(@"Button one.");
    } else if (button.tag == 1) {
       NSLog(@"Button two.");
    }
    

    您可以在三个按钮操作之前发生的方法中添加这样的内容。可能是 viewWillDisappear、prepareForSegue 等。

    祝你好运!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-12-14
      • 1970-01-01
      • 1970-01-01
      • 2012-10-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多