简体   繁体   中英

Add one to integer displayed in UILabel

I have a UILabel and when the user presses a button, I want the label to add one to its value. But I'm having a bit of trouble with this. Here is my code:

- (IBAction)addButton2:(id)sender {
    int integer = 1;
    integer++;
    [label1 setText:[NSString stringWithFormat:@"%i",integer]];
}

int doesn't respond to stringValue ...

the original question had [int stringValue] which wont work

-(IBAction)addButton2:(id)sender {
    static int myInt = 1;
    myInt++;
    NSString *string = [NSString stringWithFormat:@"%d", myInt];
    [label setText:string];  
}

Add static to your int, then the integer only will be initialized once.

- (IBAction)addButton2:(id)sender 
{
    static int integer = 1;
    integer++;
    [label1 setText:[NSString stringWithFormat:@"%d", integer]];
}

You are resetting integer to 1 every time the Button is pressed, then increase it by one. This will always result into 2 being displayed on the label. You will need to move the initialization outside of this function:

- (void)viewDidLoad
{
    [super viewDidLoad];
    integer = 1;
    [label1 setText:[integer stringValue]];
}

- (IBAction)addButton2:(id)sender
{
    integer++;
    [label1 setText:[integer stringValue]];  
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM