IOS开发之延迟执行---妙用篇

来源:互联网 发布:华为p10如何开启4g网络 编辑:程序博客网 时间:2024/05/01 19:48

项目有这样的需求:一个包含GridView的页面,顶部有一个全选按钮,点击后Gridview中所有的Button全选,这时还有计算出这些Button所表示的实物的大小,并显示到底部Label。我的计算过程实在[tableview reloaddata]实现的,开始时我在调用[tableview reloaddata]之后,调用刷新底部区域的方法,结果,总是显示上一次刷新的结果。我猜[tableview reloaddata]是个异步操作,他下面的代码,并不会再它执行完后才执行。于是想到了必须用延迟执行才可以,正确刷新底部区域。

可能描述的需求,大家有点不明白,来张图:



上代码:

-(void) onTapAllSelect:(id)sender{


        UIButton* allSelectBtn = (UIButton*) sender;

        allSelectBtn.selected = !allSelectBtn.selected;

        if (allSelectBtn.selected) {//由全选触发

            [allSelectBtn setTitle:@"取消" forState:UIControlStateSelected];

            IsAllSelected =YES;

            

        }else{

            [allSelectBtn setTitle:@"全选" forState:UIControlStateNormal];

            IsAllSelected = NO;

        }

        // delay excute

        [UIView animateWithDuration:0.3

                         animations:^{

                             [self.tableView reloadData];

                             

                         }

                         completion:^(BOOL finished){

                             if(finished){

                                 [self refreshBottomView];

                             }

                         }];

}

        

用Runloop实现

声明一个变量IsTableViewStillLoading
在- (UIGridViewCell *) gridView:(UIGridView *)grid cellForRowAt:(int)rowIndex AndColumnAt:(int)columnIndex{
...
if (partnum>=[self.bookPartList count]) {
        IsTableViewStillLoading = NO;
    }
}


然后
-(void) onTapAllSelect:(id)sender{
...
// delay excute
        
        IsTableViewStillLoading = YES;
        [self.tableView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
        while (IsTableViewStillLoading) {
            //[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];//时间太长了
            [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.5]];
        }
        [self refreshBottomView];
}

原创粉丝点击