0

我正在尝试创建打字机效果。我的代码工作正常。我的问题,还有这个…… UITextView 无法实时更新。这是我的代码:

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];
}
4

2 回答 2

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

于 2012-06-02T12:00:07.457 回答
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++;
}
于 2012-06-03T12:01:50.117 回答