How to pass multiple values into @selector( ) for a UIButton?

最后都变了- 提交于 2019-12-02 13:42:56

问题


In other words: I have one button with two events, how to capture UIControlEventTouchDown and UIControlEventTouchUpInside in the callback function setRedPos?

[btnRedPos addTarget:self action:@selector(setRedPos:) forControlEvents:UIControlEventTouchDown];// I want to pass in a value of 0
[btnRedPos addTarget:self action:@selector(setRedPos:) forControlEvents:UIControlEventTouchUpInside];// I want to pass in a value of 1

...

- (void) setRedPos:(UIButton*)btn
{

}

回答1:


You can't pass arbitrary parameters via target/action. The first parameter is sender, and the second (if you set it up this way) is the event. You could use the event to tell what kind of event triggered it, like so:

[btnRedPos addTarget:self action:@selector(setRedPos:forEvent:) 
    forControlEvents:UIControlEventTouchDown];
[btnRedPos addTarget:self action:@selector(setRedPos:forEvent:) 
    forControlEvents:UIControlEventTouchUpInside];


- (void) setRedPos:(id)sender forEvent:(UIEvent*)event
{
    UITouch* aTouch = [[event allTouches] anyObject];
    if( aTouch.phase == UITouchPhaseBegan ) {
        NSLog( @"touch began" );
    }
    else if( aTouch.phase == UITouchPhaseEnded ) {
        NSLog( @"touch ended" );
    }
}



回答2:


Use two separate selectors.

- (void)setRedPosDown:(UIButton *)button {
    [self setRedPos:button state:0];
}
- (void)setRedPosUp:(UIButton *)button {
    [self setRedPos:button state:1];
}

[btnRedPos addTarget:self action:@selector(setRedPosDown:) forControlEvents:UIControlEventTouchDown];
[btnRedPos addTarget:self action:@selector(setRedPosUp:) forControlEvents:UIControlEventTouchUpInside];



回答3:


The only two ways I know to achieve that in one method are: 1) the method zpasternack describes 2) Using two separate buttons one for the touch up one for the touch down and test the sender.

The first method is better in your case since it is with only one button object. The second would be useful if you were looking for one method achieving the actions of different buttons.

Try to stick the closer to the physical representation. One button but two different actions? The the code has only one button and tests the actions.



来源:https://stackoverflow.com/questions/11129611/how-to-pass-multiple-values-into-selector-for-a-uibutton

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!