2 u010025993 u010025993 于 2013.05.13 15:38 提问

IOS中如何释放subView

这些是添加到子视图中的代码,在添加之前我想要检测。

numberOfViews = [[GlobalVariable sharedInstance].itemNewsDetail count];
for (int i = 0; i < numberOfViews; i++) {
    @try{
        CGFloat xOrigin = i * 320;
        CGRect frame;
        frame.size = CGSizeMake(320, 365);
        frame.origin.x = xOrigin;
        frame.origin.y = 0;
        detailVC = [[DetailScrollVC alloc]initWithNibName:@"DetailScrollVC" bundle:nil];
        detailVC.view.frame = frame;
        [detailVC loadViewByIndex:i];
        UIFont *font = detailVC.txtBodyNews.font;
        detailVC.txtBodyNews.font = [font fontWithSize:currentFontSize];
        detailVC.txtBodyNews.tag = i;
        [scrollDetail addSubview:detailVC.view];
        [scrollDetail sizeToFit];
        [detailVC.view release];
    }@catch (NSException *exception) {
        NSLog(@"ERROR HANDLING : %@",exception);
    }
}

如何检测和释放以前添加过的子视图?

谢谢。

2个回答

KindAzrael
KindAzrael   2013.05.13 23:38
已采纳

递归判断view所有层的子view种是否包含目标view

@interface UIView (Extend)

- (BOOL)containSubview:(UIView *)view;

@end

@implementation UIView (Extend)

- (BOOL)containSubview:(UIView *)view {
  BOOL isContained = NO;

  if([self.subviews containsObject:view]) {
    isContained = YES;
  } else {
    if (self.subviews.count > 0) {
      for (UIView *subview in self.subviews) {
        if ([subview containSubview:view]) {
          isContained = YES;
          break;
        }
      }
    }
  }

  return isContained;
}
@end

删除子view

[subView removeFromSuperView];
zhanglei5415
zhanglei5415   Rxr 2013.05.13 16:30

检测一个视图是否还存在可以用下面的语句来判断

if (subview !=nil) {....}

如果想要释放以前的子视图,你可以先Find再从主视图中移除

UIView *subView=(UIView*)[self.view viewWithTag:123];
if (subView && [subView superView]) {
     [subView removeFromSuperView];
     subView=nil;
}
Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!