簡體   English   中英

如何將子視圖順序添加到UIScrollView

[英]How to add subviews to UIScrollView sequentially

我在將子視圖順序添加到滾動視圖時遇到問題。

我從服務器返回了一個JSON響應,我將其解析為Business對象的數組,然后發送給函數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(),它將以某種方式等待整個循環結束,然后再顯示添加的子視圖。 它甚至如何知道結果數組有多長時間? 我盡力了,請幫忙。

我假設您沒有使用任何額外的線程來處理數據。 您遇到的是應用程序卡在執行您的方法。 即使您一個一個地添加子視圖(它們之間有一個睡眠),也不會執行任何其他代碼來處理您的添加。

1 您可以使用另一個線程來加載數據並添加子視圖,但這需要與主線程同步(更復雜)。

2您可以在多個調用中中斷方法。 在兩次調用load方法之間,允許執行其他代碼段,這意味着滾動視圖將能夠一對一地處理/顯示子視圖。

您將需要將您的加載方法更改為如下所示:


- (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數據會發生什么情況。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM