0

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.

4

1 回答 1

1

带数组。

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];
}

您的buttonDown:andbuttonUp:方法应如下所示:

- (void)buttonDown:(id)sender

或者

- (void)buttonDown:(UIButton *)button

无论哪种方式,sender或者button将是对已调用该方法的对象的引用。

如果你有btnFoo并且btnBar你给他们两个都buttonDown:用于着陆事件,那么senderorbutton会告诉你按下了哪个按钮来进入该方法。

为了更全面地了解发生了什么,给所有按钮一个标签,然后在方法中抛出这行代码:

NSLog(@"Button.tag = %d", button.tag);
于 2014-05-01T03:29:23.247 回答