如何将按钮标记传递给prepareForSegue

时间:2013-11-22 12:10:44

标签: iphone button xcode5 segue

在Xcode(iPhone应用程序)中,我以编程方式创建了许多按钮:

- (void)viewDidLoad
{
    [super viewDidLoad];

    // By Road Button
    byRoadButton = [UIButton buttonWithType:UIButtonTypeCustom];
    byRoadButton.tag = 3;
    byRoadButton.frame = CGRectMake(20, 246, 280.f, 40.f);
    UIImage *roadButton = [UIImage imageNamed:@"gettingHereByRoadButton.png"];
    [byRoadButton setBackgroundImage:roadButton forState:UIControlStateNormal];
    [self.view addSubview:byRoadButton];
    [byRoadButton addTarget:self action:@selector(byRoadButtonClicked) forControlEvents:UIControlEventTouchUpInside];
}

然后我检查哪个按钮被按下:@selector,并调用performSegueWithIdentifier。 NSLog在此处显示正确的按钮标签作为检查。

- (void) byRoadButtonClicked
{
    NSLog(@"Button Pushed Tag Number: %d", byRoadButton.tag);
    [self performSegueWithIdentifier:@"gettingHereSegue" sender:self];
}

但是如何将按钮标记传递给prepareForSegue?我的想法是将此标记传递给prepareForSegue,并根据标记号将相关信息传递给下一个ViewController?

我试过了:

[self performSegueWithIdentifier:@"gettingHereSegue" sender:byRoadButton.tag];

但是得到一个错误,说我试图传递一个int而不是一个id。

在我的prepareForSegue中,我有以下内容:

- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // ThIS IS WHAT I WANT TO DO - PSEUDO CODE
    //int tagNumber = sender;
    //if (tagNumber == 3)
    //{
          //Set relevant content of Object here
    //}

    //THIS IS WHAT I CURRENTLY HAVE - NO CHECK FOR TAG
    GettingHereContent *gettingHereContent = [[GettingHereContent alloc] init];
    gettingHereContent.content = @"This is my custom content based on this buttons click";

    GettingHereViewController *vc = (GettingHereViewController *)segue.destinationViewController;
    vc.gettingHere = gettingHereContent;   
}

或者,任何人都可以建议一个解决方案,或者更好的方法来做到这一点吗?

2 个答案:

答案 0 :(得分:2)

  // try This replace with your code
 [self performSegueWithIdentifier:@"gettingHereSegue" sender:byRoadButton];

-(void) prepareForSegue:(UIStoryboardSegue *)segue sender:(UIButton *)sender
{
  NSLog(@"%ld",(long)sender.tag);
}

答案 1 :(得分:0)

尝试

[self performSegueWithIdentifier:@"gettingHereSegue" sender:byRoadButton]; 

然后在prepareForSegue

if (sender.tagNumber == 3) { //Set relevant content of Object here }