Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
467 views
in Technique[技术] by (71.8m points)

iphone - UIControl - changing assigned selectors: addTarget & removeTarget

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)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 

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...