target-action uicontrolevents

后端 未结 2 1247
别跟我提以往
别跟我提以往 2021-02-05 15:27

I must be missing something obvious here but ...

UIControl has a method

- (void)addTarget:(id)target action:(SEL)action forControlEvents: (UIControlEven         


        
2条回答
  •  一向
    一向 (楼主)
    2021-02-05 16:06

    When you create your UIControl, set a value for the tag property. Then in your action function, you can determine the tag of the UIControl that called it using [sender tag]. Here's an example:

    -(void)viewDidLoad {
        UIButton *button1 = [[UIButton alloc] initWithFrame(CGRectMake(0.0,0.0,100.0,100.0)];
        button1.tag = 42;
        [button1 addTarget:self action:@selector(actionWithUIControlEvent:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:button1];
    
    
        UIButton *button2 = [[UIButton alloc] initWithFrame(CGRectMake(100.0,0.0,100.0,100.0)];
        button2.tag = 43;
        [button2 addTarget:self action:@selector(actionWithUIControlEvent:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:button2];
    
    }
    -(void)actionWithUIControlEvent:(id)sender {
         switch([sender tag]) {
         case 42:
             //Respond to button 1
             break;
         case 43:
             //Respond to button 2
             break;
         default:
             break;
         }
     }
    

提交回复
热议问题