檢測視圖層級中是否包含特定子視圖
// UIView 分類擴展
@interface UIView (FindSubview)
- (BOOL)containsSubview:(UIView *)view;
@end
@implementation UIView (FindSubview)
- (BOOL)containsSubview:(UIView *)view {
if ([self.subviews containsObject:view]) return YES;
for (UIView *sub in self.subviews) {
if ([sub containsSubview:view]) return YES;
}
return NO;
}
@end
移除子視圖
[subview removeFromSuperview]; // 自動從父視圖移除並釋放(ARC 環境下自動管理記憶體)
應用場景:重新整理視圖前清理舊子視圖
// 清除 scrollDetail 所有子視圖
for (UIView *sub in scrollDetail.subviews) {
[sub removeFromSuperview];
}
// 重新加入新子視圖...
for (int i = 0; i < count; i++) {
DetailVC *vc = [[DetailVC alloc] init...];
[scrollDetail addSubview:vc.view];
}
記憶體管理提醒
- ARC 下
removeFromSuperview 會釋放強引用,視圖無其他持有者即銷毀
- 手動釋放
[vc.view release] 在 ARC 禁止,MRC 才需手動管理
- 避免在迴圈中重複
alloc/init 同一視圖控制器,建議複用或正確釋放