UIControl - 更改分配的选择器:addTarget &移除目标

UIControl - changing assigned selectors: addTarget amp; removeTarget(UIControl - 更改分配的选择器:addTarget amp;移除目标)

本文介绍了UIControl - 更改分配的选择器:addTarget &移除目标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我需要使用吗:

-(void)removeTarget:(id)target action:(SEL)action forControlEvents:(UIControlEvents)controlEvents 

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

before I change the selector or can I just use:

-(void)addTarget:(id)target action:(SEL)action forControlEvents:(UIControlEvents)controlEvents 

我担心如果我使用 addTarget: 方法更改选择器而不使用 removeTarget: 方法,我基本上会堆叠"选择器,以便我的 UIButton 在按下时触发.

I'm concerned that if I change the selector using the addTarget: method sans the removeTarget: method that I'll essentially "stack up" selectors for my UIButton to fire when it is pressed.

推荐答案

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

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

现在如果你这样做

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

那么方法method1和method2都会被调用.

then both the methods method1 and method2 will be called.

希望这会有所帮助.

这篇关于UIControl - 更改分配的选择器:addTarget &移除目标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:UIControl - 更改分配的选择器:addTarget &移除目标

基础教程推荐