开发者

Add one to integer displayed in UILabel

I have a UILabel and when the user press开发者_如何转开发es 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]];  
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜