为什么UIView setFrame不能在iOS的for循环中工作


UIView *test=[[UIView alloc]initWithFrame:CGRectMake(20, 150, 10, 20)];
[test setBackgroundColor:[Util colorWithHexString:@"#FF00007f"]];
[self.view addSubview:test];
int testNum=0;
for(int i=0;i<50;i++){
    testNum=0;
    //do something spend 100 ms
    while(testNum<800){
        testNum+=1;
    }
    [test setFrame:CGRectMake(20, 150, 10+i*200/50, 20)];
}

我想创建一个自定义进度条。

和上面一样,但是uiview只重绘最后一个循环。

我该如何解决这个问题?然后呢?

谢谢。

将代码改为

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    int testNum=0;
    for(int i=0;i<50;i++){
        testNum=0;
        while(testNum<800){
            NSLog(@"%d",testNum);
            testNum+=1;
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [test setFrame:CGRectMake(20, 150, 10+i*200/50, 20)];
        });
    }
});

它工作,但while循环只是模拟我的项目中的块代码的情况。

实际上,花时间代码是分配列表项并初始化它的视图,所以在主线程中是必要的。

有什么建议吗?

谢谢。

你的"do something spend 100 ms"循环只需要几个周期在iPhone上执行,你的代码正在工作,但它没有拖延足够长的时间来看到任何可见的进展。

这样锁住UI线程也是很糟糕的做法。

最新更新