iOS - 如何检测按钮是否被按下两次

时间:2015-02-16 20:52:39

标签: ios objective-c uibutton

我有一个按钮,您可以按,该按钮的文本将更改。我希望能够检测用户何时再次单击该按钮,以便按钮文本将更改回其原始文本。我怎么能这样做?这是我到目前为止的代码。

//Set Text and alignment for the buttons

[nocavities setTitle:@"No cavities\n5 points" forState:UIControlStateNormal];
nocavities.titleLabel.textAlignment = NSTextAlignmentCenter;

-(IBAction)nocavitiesaction:(id)sender {

[sender setTitle:@"Whenever you visit our office cavity-free, you will receive 5 points!" forState:UIControlStateNormal];
}

我觉得在IBAction中我应该将状态改为

UIControlStateNormalPressed

但我不确定。

4 个答案:

答案 0 :(得分:2)

您可以在IBAction

中设置计数器

这样的事情:

-(IBAction)nocavitiesaction:(id)sender {

    static int count = 0;
    count ++;
    if(count % 2 != 0){
        //Set title 1
    }else{
        //Set title 2
    }
}

答案 1 :(得分:2)

  1. 打开xib文件并选择按钮。
  2. 在属性检查器下,您将找到"状态配置",选择"默认"来自下拉列表。
  3. 将按钮标题更改为"没有空洞\ n5点"

  4. 将状态配置更改为"已选择"

  5. 将标题更改为"无论何时您无空洞地访问我们的办公室,您将获得5分!"

  6. 现在按以下方式切换这些标题。

    - (IBAction)nocavitiesaction:(id)sender
    {
        UIButton * button = sender;
        button.selected = !button.selected;
    } 
    

答案 2 :(得分:1)

像这样。 declare global int flag = 1;

-(IBAction)methodName:(id)sender
{
     if(flag==1)
     {
         //set title 1
          flag=2;
     }
     else
     {
        //set  title 2
        flag=1
     }

}

答案 3 :(得分:0)

没有UIControlStateNormalPressed州,但有一个UIControlStateSelected。您可以为所选状态和正常状态设置标题,然后手动将UIButton设置为其选定状态,如下所示:

- (void)viewDidLoad {
    [self.button setTitle:@"Whenever you visit our office cavity-free, you will receive 5 points!" forState:UIControlStateNormal];
    [self.button setTitle:@"No cavities\n5 points" forState:UIControlStateSelected];
}
- (IBAction)nocavitiesaction:(UIButton*)sender {
    sender.selected = !sender.selected;
}

注意:我已将参数从id更改为UIButton,以避免必须将id转换为UIButton以检查其选定状态。并且UIButton应该是" Custom"如果你想在选择时阻止背景色调。

相关问题