UIControl - changing assigned selectors: addTarget & removeTarget

后端 未结 2 1812
予麋鹿
予麋鹿 2020-12-17 06:17

I\'m using 10 buttons in my interface and need, from time to time, to change the button\'s selector.

Am I required to use:

-(void)removeTarget:(id)ta         


        
相关标签:
2条回答
  • 2020-12-17 06:44

    Yes, you will need to remove the old target/action or both the old and new actions will be performed.

    0 讨论(0)
  • 2020-12-17 06:49

    Yes you should always remove the previously add target before assigning the new target to the button. Like this---

    UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        [btn setFrame:CGRectMake(50, 50, 200, 50)];
    
        [btn setTag:101];
        [btn addTarget:self action:@selector(method1) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:btn];
    
    
        btn = (UIButton *)[self.view viewWithTag:101];
        [btn removeTarget:self action:@selector(method1) forControlEvents:UIControlEventTouchUpInside];
        [btn addTarget:self action:@selector(method2) forControlEvents:UIControlEventTouchUpInside];
    

    now if you do this

    btn = (UIButton *)[self.view viewWithTag:101];
            [btn addTarget:self action:@selector(method2) forControlEvents:UIControlEventTouchUpInside];
    

    then both the methods method1 and method2 will be called.

    Hope this helps.

    0 讨论(0)
提交回复
热议问题