2012-01-12 56 views
2

我有顺序添加子视图到scrollview的问题。如何顺序添加子视图到UIScrollView

我有来我从中解析为业务对象的数组服务器返回一个JSON响应,和我打发到功能updateCarousel,它看起来像这样:

-(void) updateCarousel: (NSArray *)response{ 
    if(response && response.count>0){ 
     int i=0; 
     self.scrollView.hidden=NO; 
     [self.scrollView setNeedsDisplay]; 
     self.pageControl.hidden=NO; 

     [self.scrollView setContentOffset:CGPointMake(0, 0) animated:NO]; 

     for (Business *business in response){ 
      if (i >= MAX_INITAL_SEARCH_RESULTS) 
       break; 

     CGRect frame; 
     frame.origin.x = self.scrollView.frame.size.width * i; 
     frame.origin.y = 0; 

     frame.size = scrollView.frame.size; 

     CardView *cardView = [[CardView alloc] initWithBusinessData:business andFrame:frame]; 


     //I've tried the following code with and without wrapping it in a GCD queue 
     dispatch_queue_t addingQueue = dispatch_queue_create("adding subview queue", NULL); 
     dispatch_async(addingQueue, ^{ 
      [self.scrollView addSubview:cardView]; 
     }); 
     dispatch_release(addingQueue); 

     cardView.backgroundColor = [UIColor colorWithWhite:1 alpha:0];    
     i++; 

     self.scrollView.contentSize = CGSizeMake(i*(self.scrollView.frame.size.width), self.scrollView.frame.size.height); 
     self.pageControl.numberOfPages=i; 

    } 
}else{ 
    self.scrollView.hidden=YES; 
    self.pageControl.hidden=YES; 
    NSLog(@"call to api returned a result set of size 0"); 
} 

结果 - 尽管我尝试了很多东西 - 总是一样的:scrollView一次添加子视图,而不是通过循环处理。我不明白这是怎么可能的。如果我在循环结尾添加一个sleep(),它会以某种方式等待整个循环结束,然后它将子视图显示为已添加。它甚至知道结果数组有多长?我在我的智慧结束,请帮助。

回答

0

我假设你没有使用任何额外的线程来处理数据。 您遇到的情况是应用程序卡住执行您的方法。即使你逐个添加你的子视图(在它们之间有一个睡眠),也不会执行其他代码来处理你的添加。

。你可以使用另一个线程来加载数据并添加子视图,但这需要同步到主线程(更复杂)。

您可以在多次调用中打破您的方法。在加载方法的2次调用之间,允许执行其他代码段,这意味着滚动视图将能够逐个处理/显示子视图。

你需要改变你的搭载方法是这样的:


- (void)updateCarouselStep:(NSNumber*)loadIndex 
{ 
    if (response && response.count > 0) 
    { 
     // Here add only a subview corresponding to loadIndex 


     // Here we schedule another call of this function if there is anything 
     if (loadIndex < response.count - 1) 
     { 
      [self performSelector:@selector(updateCarouselStep:) withObject:[NSNumber numberWithInt:(loadIndex+1) afterDelay:0.5f]; 
     } 
    } 

} 


这仅仅是一个基本的解决问题的办法。例如,您需要考虑在完成加载前一个数据之前更新response数据会发生什么情况。

相关问题