开发者

iOS : 2 Buttons both call the same view controller. How do I find which one was clicked?

The title says most of what I'm looking for:

I have 2 buttons on my main menu that both call the same view controller. Depending on which button was clicked the view controller behaves a little differently. I thought I had the fix using NSNotificationCenter, but it won't catch anything the first time into the view controller (because it hasn't been loaded yet). Are there a开发者_如何学Gony other ways to do this?

EDIT: There seems to be some confusion, perhaps on my end. The problem is passing the information across multiple view controllers. The buttons in the Main Menu view controller CALL the second view controller, the problem is that second view controller not having any knowledge of any variables created in the Main Menu view controller.


You could add a variable to the class of the second view controller and set that variable to a value depending on which button was pressed when you initialize the second view controller:

- (IBAction) buttonPressed:(id)button
{
    //Initialize your view controller
    MyViewController* secondViewController = [[MyViewController alloc] init...];

    //Assign a value to a variable you create (I called it pushedButtonValue) so the
    //viewController knows which button was pressed
    secondViewController.pushedButtonValue = [button tag];

    //Transition to the new view controller
    [self.navigationController pushViewController:secondViewController animated:YES];
}


The event handler for the button press will usually have an (id)sender parameter. Use this to determine which button was pressed based .

- (IBAction)pushButton:(id)sender {
    UIButton *button = (UIButton *)sender;
}


set up IBOutlets for each button and then test which sender is which button. But best way to do this it to have IBActions for each button to trigger, they then can call a method with a BOOL or enum telling the method how to behave, or do any of the different type of processing themselves and call a method that does the common code.


Alternatively, you could set a tag for each button, preferably using a typedef or enum (for clarity). In the action method compare the value of the tag. You might have to typecast the sender object to a UIButton first.

See: How to set a UIButton tag with NSString?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜