Domanda

I hope that this question's answer is as simple as the question itself.

I have a sound effect in an AVAudioPlayer that I want to play when every button is pressed. Now rather than manually adding a target to play that audio file to every button in my code, is there a way where I can override the touchUpInside event method (perhaps in an extension category file) and send the call to the AVPlayer in addition to sending the call to the super?

I don't want to have to subclass if I don't have to. Is there a delegate method I can use?

È stato utile?

Soluzione

From any class that has a reference to the view which contains the buttons as subviews, you can just iterate through all of the subviews and see which ones are UIButtons:

for (id subview in _buttonView.subviews)
    if ([subview isKindOfClass:[UIButton class]])
        [(UIButton *)subview addTarget:self 
                             selector:@selector:(playSound)    
                             forControlEvents:UIControlEventTouchUpInside];

Altri suggerimenti

In such cases, the best way is to subclass the parent view of your button view. If you are adding the buttons in a UIView class, then subclass your class from UIView. So, you will have to change only one place in the code.

Now, in the subclass override this method:

- (void)didAddSubview:(UIView *)subview;

It will get called when any of the subviews will be added to it. Identify the proper subview in the method and do any processing over the subview which you want.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top