我有一个滚动视图,我需要在我的应用运行时经常重新加载内容。现在,我正在使用以下代码行删除子视图,然后再将它们添加回来:
[scrollView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
我应该使用以下内容吗?
scrollView.subviews = nil;
出于某种原因,上面的第一行代码似乎每运行16次就会使应用程序崩溃。我在某处泄漏记忆吗?以下方法采用视图数组,滚动条(常量)和方向。
修改
- (void)loadViews:(NSArray *)views IntoScroller:(UIScrollView *)scroller withDirection:(NSString *)direction{
//Set up the scrollView
[scrollView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
if([direction isEqualToString:@"horizontal"]){
scrollView.frame = CGRectMake(0, 0, 1024, 768);
scrollView.contentSize = CGSizeMake(scrollView.frame.size.width * [[NSNumber numberWithUnsignedInt:[views count]] floatValue], scrollView.frame.size.height);
}else if([direction isEqualToString:@"vertical"]){
scrollView.frame = CGRectMake(0, 0, 1024, 768);
scrollView.contentSize = CGSizeMake(scrollView.frame.size.width, scrollView.frame.size.height * [[NSNumber numberWithUnsignedInt:[views count]] floatValue]);
}
for (int i=0; i<[[NSNumber numberWithUnsignedInt:[views count]] intValue]; i++) {
[[[views objectAtIndex:[[NSNumber numberWithInt:i] unsignedIntValue]] view] setFrame:scrollView.frame];
if([direction isEqualToString:@"horizontal"]){
[[[views objectAtIndex:[[NSNumber numberWithInt:i] unsignedIntValue]] view] setFrame:CGRectMake(i * [[views objectAtIndex:[[NSNumber numberWithInt:i] unsignedIntValue]] view].frame.size.width, 0, scrollView.frame.size.width, scrollView.frame.size.height)];//CGRectMake(i * announcementView.view.frame.size.width, -scrollView.frame.origin.x, scrollView.frame.size.width, scrollView.frame.size.height)];
}else if([direction isEqualToString:@"vertical"]){
[[[views objectAtIndex:[[NSNumber numberWithInt:i] unsignedIntValue]] view] setFrame:CGRectMake(0, i * [[views objectAtIndex:[[NSNumber numberWithInt:i] unsignedIntValue]] view].frame.size.height, scrollView.frame.size.width, scrollView.frame.size.height)];
}
[scrollView addSubview:[[views objectAtIndex:[[NSNumber numberWithInt:i] unsignedIntValue]] view]];
}
}
答案 0 :(得分:4)
您提供的第一个示例是从UIScrollView
删除子视图的正确方法。
[scrollView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
将subviews
设置为nil
可以有效地清除管理子视图的集合对象,从而无法添加新的子视图。
答案 1 :(得分:1)
以下是从滚动视图中删除所有子视图的代码:
for(UIView *subview in [scrollview subviews])
{
[subview removeFromSuperview];
}