如何防止双击 UIButton 按钮取消操作?

发布于 2024-12-09 20:09:16 字数 883 浏览 1 评论 0原文

我有一个 UIButton,单击它后开始搜索数据。但是在搜索时,如果用户再次单击该按钮,则会取消搜索。

相关代码:

    - (void)searchAction:(UIButton *)sender {

    [sender removeTarget:self action:@selector(searchAction:) forControlEvents:UIControlEventTouchUpInside];
    [sender addTarget:self action:@selector(cancelSearch:) forControlEvents:UIControlEventTouchUpInside];  
    [animatedImages startAnimating];
    //action that should be done

}

- (void)cancelSearch:(UIButton *)sender {
    [sender removeTarget:self action:@selector(cancelSearch:) forControlEvents:UIControlEventTouchUpInside];
    [sender addTarget:self action:@selector(searchNearbyAction:) forControlEvents:UIControlEventTouchDown];
    [animatedImages stopAnimating];

}

所以基本思想是,当我单击它时,它的功能更改为取消,反之亦然。

问题是,当我第一次单击它时,它调用 searchAction 然后调用 <无缘无故地代码>cancelSearch。

有谁知道为什么会发生这种情况?

I have a UIButton that when clicked starts searching for data. But while searching, if the user clicks on the button again it cancels the search.

Relevant Code:

    - (void)searchAction:(UIButton *)sender {

    [sender removeTarget:self action:@selector(searchAction:) forControlEvents:UIControlEventTouchUpInside];
    [sender addTarget:self action:@selector(cancelSearch:) forControlEvents:UIControlEventTouchUpInside];  
    [animatedImages startAnimating];
    //action that should be done

}

- (void)cancelSearch:(UIButton *)sender {
    [sender removeTarget:self action:@selector(cancelSearch:) forControlEvents:UIControlEventTouchUpInside];
    [sender addTarget:self action:@selector(searchNearbyAction:) forControlEvents:UIControlEventTouchDown];
    [animatedImages stopAnimating];

}

So the basic idea is that when i click on it its function change to cancel and vice-verca

The problem is that when I click on it the first time, it calls searchAction and then calls cancelSearch for no reason.

Does anyone know why this might be happening?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

绮烟 2024-12-16 20:09:16

解决方法是添加 BOOL 作为实例变量

BOOL canCancel;

,然后执行以下操作

- (void)buttonClicked:(UIButton *)sender {
      if (!canCancel) {
           // action that should be done
           canCancel = YES;
      } else if (canCancel) {
           // cancel action
           canCancel = NO;
      }
}

A workaround is to add a BOOL as an instance variable

BOOL canCancel;

and then do the following

- (void)buttonClicked:(UIButton *)sender {
      if (!canCancel) {
           // action that should be done
           canCancel = YES;
      } else if (canCancel) {
           // cancel action
           canCancel = NO;
      }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文