2012-06-02 38 views
0

我试图创建一个打字机效果。 我的代码工作正常。我的问题,这... UITextView无法实时更新。这是我的代码:iphone textview更新while循环运行线程

NSMutableArray *testochar=[util getTestoChar:value]; 

for (int i=0; i<[testochar count]; i++){ 
    NSString *y=[testochar objectAtIndex:i]; 

    [NSThread sleepForTimeInterval:0.1f]; 

    self.txtview.text=[self.txtview.text stringByAppendingString:y]; 
} 

回答

3

在UI上所有的修改,你应该在主线程,请尝试使用performSelectorOnMainThread:withObject:waitUntilDone:

呼叫

//... 
    for(int i=0;i<[testochar count];i++){ 
     NSString *y=[testochar objectAtIndex:i]; 
     [NSThread sleepForTimeInterval:0.1f]; 
     NSDictionary *arg = [NSDictionary dictionaryWithObjectAndKeys: 
       self.txtview, @"textView", 
       y, @"string", nil ]; 
     [self performSelectorOnMainThread:@selector(updateTextForTextView:) withObject:arg waitUntilDone:NO]; 
    } 

//..... 


-(void)updateTextForTextView:(NSDictionary*)arg { 
    NSString *string = [arg objectForKey:@"string"]; 
    UITextView *textView = [arg objectForKey:@"textView"]; 
    self.txtview.text=[self.txtview.text stringByAppendingString:string]; 
} 

(更新)

尝试

- (void)viewDidLoad { 
    [super viewDidLoad]; 

    textView.text = @""; 


    [[NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(update) userInfo:nil repeats:YES] retain]; 
} 


-(void) update { 
    static char text[] = "HELLO"; 
    static int i =0; 

    if (text[i%6]==0) { 
     textView.text = [NSString stringWithFormat:@""]; 
    } else { 
     textView.text = [NSString stringWithFormat:@"%@%c", textView.text, text[i%6] ]; 
    } 
    i++; 
} 

它的工作原理是: http://www.youtube.com/watch?v=tB2YKX4zpY4

+0

偏见, 感谢您的回答,但我不能得到预期的效果。 例如: 的NSString * @ TXT = “HELLO” 结果: H(1个seocnd睡眠)和(睡眠1秒)L(睡眠1秒)和c ... 有一种方法来有这种影响? 非常感谢。 – Diego

+0

我更新了我的帖子,检查是否有你想要的东西 –

2

非常感谢您的建议。我通过这种方式修改了代码。

1)self.timer = [[NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(update) userInfo:nil repeats:YES] retain];

-(void) update { 
    char text[[self.testo length]]; 

    for(int i=0;i<self.testo.length;i++){ 
     text[i]=[self.testo characterAtIndex:i]; 
    } 

    static int i =0; 

    if (i==self.testo.length) { 
     /// txtview.text = [NSString stringWithFormat:@""]; 
     [self.timer invalidate]; 
    } else { 
     txtview.text = [NSString stringWithFormat:@"%@%c", txtview.text, text[i%self.testo.length] ]; 

    } 

    i++; 
}