xcode - if statement activated by a button?

空扰寡人 提交于 2020-01-06 06:49:34

问题


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. }


回答1:


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";
    }
}



回答2:


You should use:

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


来源:https://stackoverflow.com/questions/12964180/xcode-if-statement-activated-by-a-button

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!