xcode - if statement activated by a button?

2019-09-07 10:33发布

I am trying to have numbers change by different amounts, by the press of one button. I am new to xcode and do not know how to do this, any help would be nice.

I want the number to change to 15, but only when I press the button for a second time. Then, I would like, upon a third press, for the number to change 30.

-(IBAction)changep1:(id) sender {
p1score.text = @"5";
if (p1score.text = @"5"){

    p1score.text = @"15";

//Even if the above worked, I do not know how I would write the code to change it to 30. }

2条回答
地球回转人心会变
2楼-- · 2019-09-07 11:19

In your example code above, you are using the assignment operator = instead of the comparison operator == in your if statement. In addition, when testing NSString equality, use the isEqualToString: instance method like this:

-(IBAction)changep1:(id)sender
{
    p1score.text = @"5";

    if ([p1score.text isEqualToString:@"5"])
    {
        p1score.text = @"15";
    }
}

Keep in mind though that the code snippet above will result in p1score.text always being set to a value of @"15" since you are setting it on the line preceding the if statement which makes the condition evaluate to YES.

To make it only change the text after the first tap you can do something like this:

-(IBAction)changep1:(id)sender
{
    if ([p1score.text isEqualToString:@"5"])
    {
        p1score.text = @"15";
    }
    else
    {
        p1score.text = @"5";
    }
}
查看更多
▲ chillily
3楼-- · 2019-09-07 11:19

You should use:

if ([p1score.text isEqualToString:@"5"]){
     p1score.text = @"15";
}
查看更多
登录 后发表回答