Almudhafar
Almudhafar

Reputation: 887

Changing UIButton title or set UILabel text using for loop

I am using this code to change the title of UIButton or UILabel while the loop is running, but it is not working.

- (IBAction)do2:(id)sender
{

    for (float i = 0; i < 1000; i = i + 0.5) {

        NSLog(@"%f", i);

        [self.Lbl1 setText:[NSString stringWithFormat:@"%f", i]];
        [self.Btn1 setTitle:[NSString stringWithFormat:@"%f", i] forState:UIControlStateNormal];


    }

}

The log is printing the value, but the title didn't change. How can I fix this?

Upvotes: 0

Views: 1117

Answers (3)

Viper
Viper

Reputation: 1408

The reason is while loop executes fast and you are only able to see title changed after completion of code.

If you want to see title changing try NSTimer instead and change title from the function called from timer. e.g -

NSTimer *myTimer    =   [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(changeTitle) userInfo:Nil repeats:YES];

And in changeTitle Method -

-(void)changeTitle{
    if (GlobalCount <= 1000) {
        GlobalCount++;
        NSLog(@"%f", GlobalCount);

        [self.Lbl1 setText:[NSString stringWithFormat:@"%f", i]];
        [self.Btn1 setTitle:[NSString stringWithFormat:@"%f", i] forState:UIControlStateNormal];
    }else{
        [myTimer invalidate];
    }
}

GlobalCount is global integer value.

Upvotes: 0

Rajesh
Rajesh

Reputation: 10434

try this. issue with your code is your label and button gets updated with last value of array. the following code would resolve your problem

- (IBAction)do2:(id)sender
    {
        for (float i = 0; i < 1000; i = i + 0.5) {
       dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                 [self.Lbl1 setText:[NSString stringWithFormat:@"%f", i]];
            [self.Btn1 setTitle:[NSString stringWithFormat:@"%f", i] forState:UIControlStateNormal];
        });

        }
    }

Upvotes: 1

Prajeet Shrestha
Prajeet Shrestha

Reputation: 8108

If you want it change while the application is running like the timer app, you should use Timer for that:

NSTimer *timer;//Declare it as a instant variable somewhere

timer = [NSTimer scheduledTimerWithTimeInterval:1.0
                                 target:self
                               selector:@selector(changeText)
                               userInfo:nil
                                repeats:YES];

And define the method to run in each interval:

- (void)changeText
{
    count++;
    [self.Lbl1 setText:[NSString stringWithFormat:@"%f", count]];
    [self.Btn1 setTitle:[NSString stringWithFormat:@"%f", count] forState:UIControlStateNormal];
    if (count >= 1000)
    {

        [timer invalidate];
    }
}

Upvotes: 0

Related Questions