I know I can detect if my button is being held down by adding a selector like this

[button addTarget:self action:@selector(buttonDown:) forControlEvents:UIControlEventTouchDown];

But with 50+ buttons in a single view I have I'm trying to see if theres a way to add a selector to ALL buttons in my view and see if theres a button being held down and which button is it.

Im wondering because I need to detect UIControlEventTouchDown AND UIControlEventTouchUpInside on 50+ buttons so thats a lot of code id like to shorten down.

有帮助吗?

解决方案

With arrays.

for (UIButton *button in self.arrayOfButtons) {
    [button addTarget:self 
               action:@selector(buttonDown:) 
     forControlEvents:UIControlEventTouchDown];

    [button addTarget:self 
               action:@selector(buttonUp:)  // it's cold outside
     forControlEvents:UIControlEventTouchUpInside];
}

Your buttonDown: and buttonUp: methods should look like this:

- (void)buttonDown:(id)sender

OR

- (void)buttonDown:(UIButton *)button

Either way, sender or button is going to be a reference to the object that has called the method.

If you have btnFoo and btnBar and you give both of them buttonDown: for the touch down event, then sender or button will tell you WHICH button was pressed to get into the method.

To more completely see what's going on, give all your buttons a tag, and throw this line of code in the method:

NSLog(@"Button.tag = %d", button.tag);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top