iOS将子视图添加到滚动视图

时间:2012-07-19 15:27:25

标签: ios xcode

我正在使用双循环将UIButtons以网格格式添加到UIScrollView。这些UIButton需要时间来加载,因为它们具有UIImageViews的子视图,它们通过从互联网上下载数据来获取它们的UIImages。

现在,在方法完全执行完之后,子视图才会显示。如果我错了,请纠正我,但我猜测xcode在方法执行完毕之前不会显示添加的子视图。

但是,我确实想要显示每个子视图一次添加一个,作为一个很酷的加载效果。我该如何实现呢?

谢谢!

1 个答案:

答案 0 :(得分:3)

您应该使用多个线程来加载图片,这样您的主线程就不会变得迟钝。我最近写了类似的东西......看看我的viewWillAppear方法中的代码:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    self.myImages = [self.myModel retrieveAttachments]; //Suppose this takes a long time
    for (UIImage *image in self.myImages) 
    {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self addImageToScrollView:image animated:YES]; });
    }
}
});

addImageToScrollView方法如下:

-(void) addImageToScrollView: (UIImage *) image animated: (BOOL) animated
{
    //Create image view
    UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
    imageView.image = image;

    if(animated)
    {
        imageView.alpha = 0;
        [self.myScrollView addSubview:imageView];
        [UIView animateWithDuration:ADD_IMAGE_APPEARING_ANIMATION_SPEED animations:^{
            imageView.alpha = 1;
        }];
    }
    else
    {
        [self.myScrollView addSubview:imageView];
    }
}
相关问题