ios 移除特定的子視圖或移除所有子視圖

分類:技術 時間:2017-01-13

視圖層移除

如果要移除一個 UIView 的所有子視圖

for(UIView *view in [self.view subviews])
    {
        [view removefromsuperview];
    }

如果要移動指定類型的視圖

for(UIView *mylabelview in [self.view subviews])
{
    if ([mylabelview isKindOfClass:[UILabel class]]) {
        [mylabelview removeFromSuperview];
    }
}

如果你是想找到某個視圖中的一個特定的子視圖,并且將其移除,方法如下:

//依次遍歷self.view中的所有子視圖
for(id tmpView in [self.viewsubviews])
{
    //找到要刪除的子視圖的對象
    if([tmpView isKindOfClass:[UIImageViewclass]])
    {
        UIImageView *imgView = (UIImageView *)tmpView;
        if(imgView.tag == 1)   //判斷是否滿足自己要刪除的子視圖的條件
        {
            [imgView removeFromSuperview]; //刪除子視圖

            break;  //跳出for循環,因為子視圖已經找到,無須往下遍歷
        }
    }
}

如果你是想徹底釋放此視圖,直接release或者autorelease就可以了。

拓展:

- (void)addSubview:(UIView *)view 
//添加子視圖
- (void)removeFromSuperview 
//從父視圖中移除

- (void)bringSubviewToFront:(UIView *)view
//移動指定的子視圖到最頂層
- (void)sendSubviewToBack:(UIView *)view
//移動制定的子視圖到后方,所有子視圖的下面

- (void)insertSubview:(UIView *)view atIndex:(NSInteger)index
//在指定的位置插入子視圖,視圖的所有視圖其實組成了一個數組
- (void)insertSubview:(UIView *)view aboveSubview:(UIView *)siblingSubview
//將指定的子視圖移動到指定siblingSubview子視圖的前面
- (void)insertSubview:(UIView *)view belowSubview:(UIView *)siblingSubview
//將指定的子視圖移動到指定siblingSubview子視圖的后面
- (void)exchangeSubviewAtIndex:(NSInteger)index1 withSubviewAtIndex:(NSInteger)index2
//交換兩子視圖的位置

- (BOOL)isDescendantOfView:(UIView *)view
//判斷接收對象是否是指定視圖的子視圖,或與指定視圖是同一視圖

此外

insertSubview:atIndex: (放到index層,越往下,index越小)

insertSubview:A aboveSubview:B(把前一個ViewA放在后一個ViewB 的上面)

insertSubview:A belowSubview:B(把前一個ViewA放在后一個ViewB 的下面)

整理

bringSubviewToFront: (把一個View放到上面)

sendSubviewToBack:(把一個View放到下面)

exchangeSubviewAtIndex:withSubviewAtIndex:(來修改遮擋。我的理解是view按照控件加進去的順給了個index,這個index從0開始遞增。顯示的時候index數值較大控件遮擋數值較小的。 上面這個函數交換兩個控件位置)

刪除

removeFromSuper view(從父類中刪除)

感謝關注!


Tags: iOS開發

文章來源:http://www.jianshu.com/p/cea4a214f702


ads
ads

相關文章
ads

相關文章

ad