简体   繁体   中英

Set The Target and Selector of a Button to Multiple Methods

I want to add multiple methods in that respond as the selector when a button is pressed. Can one button have two methods that get called when the button is pressed?

Through my research, I found, in the objective-C Programming Language Guide, that a button will call All methods with the same name as the selector.

I want my button to do two actions at the same time:

  1. play the audio file
  2. display views in array.

    UIBarButtonItem *play = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemPlay target:self action:@selector(play:)];

Appreciate advice.

Thanks

@selector() literally just returns a SEL value, which is just a name (in fact, under the hood, it's literally a string). It doesn't specify any particular behavior. Classes choose how to respond when they're sent a selector.

You could certainly have a class implement a method that does two things and set the selector for that method to be a control's action:

- (void)eatCakeAndIceCream {
    [self eatCake];
    [self eatIceCream];
}

You can also add multiple actions to a control with repeated calls of addTarget:action:forControlEvents: :

[someControl addTarget:self action:@selector(eatCake) forControlEvents:UIControlEventTouchDown];
[someControl addTarget:self action:@selector(eatIceCream) forControlEvents:UIControlEventTouchDown];

You can specify multiple target-action pairs for a particular event.

[btn addTarget:self action:@selector(playSound:) forControlEvents:UIControlEventTouchUpInside];
[btn addTarget:self action:@selector(displayViews:) forControlEvents:UIControlEventTouchUpInside];

Every time you add a target to a object, it creates a control object (also called 'action message') (control object is of type UI control). This control object contains the name of the selector called 'action selector' and the target on which this selector needs to be invoked. This control object then gets bind (registered) with a specified event. You can bind multiple control objects to the same event. Which means I can have 2 target with two selectors bint to the same event.

Example

[btn addTarget:oneTarget action:@selector(foo:) forControlEvents:UIControlEventTouchUpInside];

[btn addTarget:twoTarget action:@selector(bar:) forControlEvents:UIControlEventTouchUpInside];

At runtime all of these control messages bind into the give event will be dispatched to the appropriate target, in other words all these selector methods will be invoked on their respective target class objects.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM