Question

Goal is to enumerate every character in the String. That is 'w' will appear then after 1 sec will be replaced by 'h' then 'e' then 'n'. Problem my label only shows the last letter.

What i did: 1. drag a label and a button on the PlayViewController. 2. create the property for Label 3. create action for button

In my PlayViewController.h:

#import <UIKit/UIKit.h>

@interface PlayViewController : UIViewController

@property (strong, nonatomic) IBOutlet UILabel *listChar;

- (IBAction)startGame:(id)sender;

@end

In my PlayViewController.m:

#import "PlayViewController.h"

@interface PlayViewController ()

@end

@implementation PlayViewController

NSString *word;
NSTimer *myTimer;

- (void)viewDidLoad 
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.listChar.text = @" ";
    word = @"when";

}

- (IBAction)startGame:(id)sender {
    myTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(listLetter:) userInfo:nil repeats:YES];
}


-(void) listLetter:(NSTimer*) myTimer {
    for(int i=0; i<[word length]; i++){
        unichar letter = [word characterAtIndex: i];
        self.listChar.text = [NSString stringWithFormat:@"%C", letter];
    }
}

@end
Was it helpful?

Solution

If you want to know about why this happning then refer @Nitin's answer, and if you want to solve in other way then just use following code

-(void) listLetter:(NSTimer*) myTimer
    static int pos = 1;
    self.listChar.text = [word substringToIndex:pos];
    if (++pos > word.length) {
        [myTimer invalidate];
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top