2012-01-12 58 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數據會發生什麼情況。

相關問題