iphone - Change UILabel in loop -
i want change uilabel after 2 sec in loop. current code change last value after loop finished.
- (ibaction) start:(id)sender{ (int i=0; i<3; i++) { nsstring *tempstr = [[nsstring alloc] initwithformat:@"%s", @" "]; int randomnumber = 1+ arc4random() %(3); if (randomnumber == 1) { tempstr = @"red"; }else if (randomnumber == 2) { tempstr = @"blue"; } else { tempstr = @"green"; } nslog(@"log: %@ ", tempstr); labelstext.text = tempstr; [tempstr release]; sleep(2); } }
your code updates label last value function blocks main thread ui cannot updated. solve problem move updating code separate function , call using performselector:withobject:afterdelay:
method. (or schedule calls using nstimer
)
possible solution (you need handle case when user taps button several times in row, should not difficult):
- (ibaction) start:(id)sender{ [self updatelabel]; } - (void) updatelabel{ static const nsstring* allstrings[] = {@"red", @"blue", @"green"}; static int count = 0; int randomnumber = arc4random()%3; nsstring *tempstr = allstrings[randomnumber]; nslog(@"log: %@ ", tempstr); labelstext.text = tempstr; ++count; if (count) [self performselector:@selector(updatelabel) withobject:nil afterdelay:2.0]; }
Comments
Post a Comment