2012-01-12 2 views
2

하위 뷰를 순차적으로 스크롤 뷰에 추가하는 데 문제가 있습니다.순차적으로 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

데이터 처리를 위해 추가 스레드를 사용하지 않는다고 가정합니다. 응용 프로그램에서 메서드 실행이 멈췄습니다. 하위보기를 하나씩 추가하더라도 (그 사이에 잠을 자면) 추가를 처리 할 다른 코드는 실행되지 않습니다.

. 다른 스레드를 사용하여 데이터를로드하고 하위 뷰를 추가 할 수 있지만 주 스레드와 동기화해야합니다 (더 복잡합니다).

여러 통화에서 메소드를 중단 할 수 있습니다. 로드 메소드를 두 번 호출하는 사이에 다른 코드가 실행될 수 있으며 이는 스크롤 뷰가 하나씩 하위 뷰를 처리/표시 할 수 있음을 의미합니다. 당신은 이런 식으로 적재 방법을 변경해야합니다

는 :


- (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 데이터를 업데이트하면 어떤 일이 발생하는지 고려해야합니다.

관련 문제