【问题标题】:Remove Subview from Superview从 Superview 中删除子视图
【发布时间】:2014-07-24 12:52:53
【问题描述】:

我真的被这个问题困扰了很长时间

我正在尝试将UIControl(最后是UIView)添加到我自己的类中有子类的UITableViewCell(我创建了一个自定义单元格)

在滑动时,我创建了我的 UIControl 类并将其添加到我自己(单元格)中,到目前为止一切顺利。这是代码

[self addSubview:_statusView];

但是,我在自定义单元格中向我的UIControl 添加了一个目标操作,以便当UIControl 说他已经识别出一个 touchDownEvent 时,该单元格可以处理。

[self.statusView addTarget:self action:@selector(resetAll:) forControlEvents:UIControlEventTouchDown];

这是我想在动作中做的,我想从self.subviews(单元格的子视图)中删除UIControl,所以我将动作方法设置为这样

- (void)resetAll:(id)sender
{
for (UIView *view in self.subviews) {
    if ([view isKindOfClass:[StatusView class]]) {
        [view removeFromSuperview];
    }
}
}

有人能指出这段代码有什么问题吗?因为我真的不明白为什么添加到单元格的视图没有被删除。在我看来, subviews 属性从未包含我添加的UIControl

【问题讨论】:

  • 是你的 resetAll: 选择器被调用
  • 为什么不直接打电话给[sender removeFromSuperview]
  • resetALL: 确实被调用了。 sender 是活动吗?它不是我要删除的UIView
  • -(void)resetAll:(UIView *)sender { [sender removeFromSuperview]; }.
  • 为什么我在这个问题上得到了-1的声誉?这个网站有时有点迟钝。

标签: ios uiview subview superview


【解决方案1】:
- (void)resetAll:(id)sender
{
for (UIView *view in self.view.subviews) {
    if ([view isKindOfClass:[StatusView class]]) {
        [view removeFromSuperview];
    }
}
}

- (void)resetAll:(id)sender
{
[sender removeFromSuperview];
}

【讨论】:

  • 第一个解决方案不能作为 resetAll: 方法在 UITableViewCell 上调用并且它没有 view 属性
  • self.view.subviews 是什么意思? self 已经是 UIView 的单元格。
  • 它对我有用。谢谢!for (UIView *view in self.view.subviews) { if ([view isKindOfClass:[StatusView class]]) { [view removeFromSuperview]; } }
【解决方案2】:

UITableViewCell 在内部对其视图层次结构进行一些操作。您不应该将子视图添加到单元格本身,而是添加到其contentView,如docs 中所述:

如果你想超越预定义的样式,你可以添加子视图 到单元格的 contentView 属性。

所以你必须更换

[self addSubview:_statusView];

[self.contentView addSubview:_statusView];

然后迭代contentView的子视图:

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

【讨论】:

  • 我发现的最简单的解决方案,比子类化要容易得多。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多