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

iOS - How to Detect if Button is Pressed Twice

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

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

但我不确定。

您可以在 IBAction

中设置一个计数器

像这样:

-(IBAction)nocavitiesaction:(id)sender {

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

没有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" 类型,如果你想在选择时防止背景色调。

  1. 打开 xib 文件和 select 按钮。
  2. 在属性检查器下,您会从下拉列表中找到 "State Config"、select "Default"。
  3. 将按钮的标题更改为"No cavities\n5 points"

  4. 将状态配置更改为 "Selected"

  5. 将标题更改为 "Whenever you visit our office cavity-free, you will receive 5 points!"

  6. 现在切换这些标题。

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

像这样。 声明全局 int 标志=1;

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

}