简体   繁体   中英

UILabel int count ++ doesn't work

I'm trying to indefinitely count up a number of taps on a UILabel , every time the label is tapped a different string is displayed. However, it stops at 2 taps always using ++ or += 1

 -(void)cycleLabelString {
    int taps;
    taps += 1;
    NSLog(@"taps = %d", taps);

    if (taps == 1) {
        self.randomLabel.text = [NSString stringWithFormat:@"$%.2f", pagesCount * 0.69];
    } else if (taps == 2) {
        self.randomLabel.text = [NSString stringWithFormat:@"%d", pagesCount];
    } else if (taps >= 3) {
        NSLog(@" >= 3");
    }
}
int taps;

This initializes a new taps each time, and it is initialized to zero by default. You probably want it in a property. Make a private class extension at the top of your .m file like this:

@interface YourClassNameHere ()

@property (nonatomic) int taps;

@end

And then to use it:

-(void)cycleLabelString {
    self.taps += 1;
    NSLog(@"taps = %d", self.taps);

    if (self.taps == 1) {
        self.randomLabel.text = [NSString stringWithFormat:@"$%.2f", pagesCount * 0.69];
    } else if (self.taps == 2) {
        self.randomLabel.text = [NSString stringWithFormat:@"%d", pagesCount];
    } else if (self.taps >= 3) {
        NSLog(@" >= 3");
    }
}

is this function getting called everytime the label is tapped? if so, you will need to define taps as a global variable, as it is being reset everytime the label is tapped. try something like:

int taps;

-(void)cycleLabelString {
...

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