问题
I have looked into this, but I’m still not quite clear how to do it. I have a UILabel. I would like to write out a word... letter by latter. It goes through each letter, then at the end the entire word shows up. At first I thought it was just because it was too fast, so I put in a delay with something like this.
typedWord.text = [typedWord.text stringByAppendingString:@"C"];
future = [NSDate dateWithTimeIntervalSinceNow: letterPause ];
[NSThread sleepUntilDate:future];
Then I read that it may be because it doesn’t refresh until the function call is finished. The suggestion was to use a selector call. I’m not sure how to do this. Any suggestions?
回答1:
You are sleeping the main thread, so the UI is not getting refreshed until the end of the sleep.
You need to implement something like the following:
// This code is in your view controller somewhere, where you initially decide to update the label. typedWord is the outlet to your UILabel.
NSString *newText = @"Hello";
typedWord.text = @"";
[self performSelector:@selector(updateLabel:) withObject:newText afterDelay:0.2];
This calls:
// This is a separate method in your view controller, so typedWord still refers to the label outlet.
-(void)updateLabel:(NSString*)newText
{
// Get the first character of the passed in string
NSString *firstCharacter = [newText substringToIndex:1];
// Add this to whatever the current label text is
typedWord.text = [NSString stringWithFormat:@"%@%@",typedWord.text,firstCharacter];
// Trim off the first character
NSString *remainingCharacters = [newText stringByReplacingCharactersInRange:NSMakeRange(0,1) withString:@""];
//If we still have characters left, do the loop again.
if (![remainingCharacters isEqualToString:@""])
[self performSelector:@selector(updateLabel:) withObject:remainingCharacters afterDelay:0.2];
}
来源:https://stackoverflow.com/questions/8197406/uilabel-refresh