UIControl - 更改分配的选择器:addTarget&removeTarget

sam*_*u_1 3 iphone cocoa-touch objective-c uibutton uicontrol

我在我的界面中使用了10个按钮,并且需要不时地更改按钮的选择器.

我需要使用:

-(void)removeTarget:(id)target action:(SEL)action forControlEvents:(UIControlEvents)controlEvents 
Run Code Online (Sandbox Code Playgroud)

在我更改选择器之前或者我可以使用:

-(void)addTarget:(id)target action:(SEL)action forControlEvents:(UIControlEvents)controlEvents 
Run Code Online (Sandbox Code Playgroud)

我很担心,如果我使用addTarget改变选择:方法SAN的removeTarget:方法,我会基本上是"堆起来"我的UIButton被按下时,它开火选择.

Mad*_*dav 12

是的,在将新目标分配给按钮之前,应始终删除先前添加的目标.像这样 - -

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];
Run Code Online (Sandbox Code Playgroud)

现在,如果你这样做

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

然后将调用方法method1和method2.

希望这可以帮助.

  • 谢谢.我注意到apple docs声明为action:参数"传递NULL"删除了与目标配对的所有动作方法.如果removeTarget:方法的接收器是UIButton并且目标是self(在viewController中调用)将删除所有绑定的方法到那个UIButton?因为我只为每个按钮分配一个方法,所以我需要做的就是在action:parameter中传递NULL ...在这种情况下,这与引用要删除的确切方法不同你在上面的例子中做了什么? (2认同)