从一个视图中删除视图并将其添加到另一个视图

时间:2012-06-15 03:24:31

标签: ios objective-c uiview addsubview

我正在尝试查找笔尖中的所有视图,并将它们添加到我的内容视图中。

这就是我所拥有的,它成功地从self.view中删除了视图,但它没有将它添加到self.contentView

for (UIView *view in self.view.subviews) {
    if (view.tag != 666) {
        [view removeFromSuperview];
        [self.contentView addSubview:view];
    }
}

任何帮助都将不胜感激。

7 个答案:

答案 0 :(得分:5)

代码中的问题是,当您调用removeFromSuperview时,父视图将释放该视图。无需调用removeFromSuperview,只需将其添加为另一个视图的子视图,就会将其从当前的parentView中删除。

所以使用:

for (UIView *view in self.view.subviews)
{
    if (view.tag != 666)
    {
        [self.contentView addSubview:view];
    }
}

根据UIView Class Reference

  

<强> addSubview

     

将视图添加到接收者的子视图列表的末尾。

     

- (void)addSubview:(UIView *)view

     

<强>参数

     

视图

The view to be added. This view is retained by the receiver. After being added, this view appears on top of any other subviews. 
     

讨论

     

此方法保留视图并将其下一个响应者设置为接收者,   这是它的新超级视图。

     

视图只能有一个超级视图。如果视图已经有超视图和   该视图不是接收者,此方法删除了以前的   在使接收器成为新的超级视图之前的超视图

答案 1 :(得分:0)

我不确定这是否有效,但请尝试切换[view removeFromSuperview];[self.contentView addSubview:view];。这是因为根据UIView Class ReferenceremoveFromSuperview会导致superview释放视图。

希望这有帮助!

答案 2 :(得分:0)

检查错误。 您最好打印这些视图的框架(self.view,self.contentView)。 并使它们成为不同的颜色。 然后你可以看到错误。 祝你好运!

答案 3 :(得分:0)

contentView不属于UIVew的属性。它属于UITableViewCell的财产。它返回单元格对象的内容视图。

答案 4 :(得分:0)

  for (UIView *v in innerMainView.subviews)
    {
        [v removeFromSuperview];
    }   
    [innerMainView addSubview:StandardView];

答案 5 :(得分:0)

您可以将指定的视图设置为属性,也可以在将视图从超级视图中删除之前将其添加到内容视图中。我不确定何时删除视图,如果视图的保留计数减少到0,它将调用超级视图来解除它。

答案 6 :(得分:0)

当您从superView移除视图时,releasememory。所以在你的情况下你需要这样做:

UINib *infoNib = [UINib nibWithNibName:@"YourXIBFileName" bundle:nil];

NSArray *topLevelObjects = [infoNib instantiateWithOwner:self options:nil];

UIView *infoView = [topLevelObjects objectAtIndex:0];
for (UIView *view in infoView.subviews) {
        [self.contentView addSubview:view];
    }
}
相关问题