在运行时从UIScrollView / PageControl中删除视图/控制器

时间:2011-03-03 00:39:32

标签: iphone objective-c uiscrollview uipagecontrol

我正在使用scrollview和pagecontrol来渲染多个图像,非常类似于内置的照片应用。我正在使用此代码在视图加载时设置控制器:

NSMutableArray *controllers = [[NSMutableArray alloc] init];
for (unsigned i = 0; i < [photos count]; i++) {
    [controllers addObject:[NSNull null]];
}
self.viewControllers = controllers;
[controllers release];

scrollArea.pagingEnabled = YES;
scrollArea.contentSize = CGSizeMake(newW * [photos count], newH);
scrollArea.showsHorizontalScrollIndicator = NO;
scrollArea.showsVerticalScrollIndicator = NO;
scrollArea.scrollsToTop = NO;
scrollArea.delegate = self;

pageControl.numberOfPages = [photos count];

newW和newH只是我用来跟踪方向变化时的大小的两个变量。 我的loadScrollViewWithPage方法:

- (void) loadScrollViewWithPage:(int)page {
    if (page < 0) return;
    if (page >= [photos count]) return;

    PhotoViewController *controller = [viewControllers objectAtIndex:page];

    if ((NSNull *)controller == [NSNull null]) {
        controller = [[PhotoViewController alloc] init];
        controller.imgPath = (NSString *)[photos objectAtIndex:page];
        [viewControllers replaceObjectAtIndex:page withObject:controller];
        [controller release];
    }

    if (nil == controller.view.superview) {

        CGRect frame = scrollArea.frame;
        frame.origin.x = frame.size.width * page;
        frame.origin.y = 0;
        controller.view.frame = frame;
        [scrollArea addSubview:controller.view];        
    }
}

这是我的问题。我需要在需要时卸载控制器/视图。我以为我可以使用这样的东西:

for (unsigned i = 0; i < [photos count]; i++) {
    [self.viewControllers replaceObjectAtIndex:i withObject:[NSNull null]];
}

我想这样做,所以在scrollview中加载全新的视图。

我也尝试了一些没有运气的事情:

for(UIView *subview in [self.scrollArea subviews]) {
 [subview removeFromSuperview];
}

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

因此,您希望在更新后者时确保scrollView的子视图与self.viewControllers中的项保持同步?最简单的方法是在替换其中一个项目时执行类似的操作:

UIViewController *vc = [self.viewControllers objectAtIndex:i];
if ((NSNull *)vc != [NSNull null] && [vc isViewLoaded]) [vc.view removeFromSuperview];
[self.viewControllers replaceObjectAtIndex:i withObject:foo];