【问题标题】:removeFromSuperview UIImageView not workingremoveFromSuperview UIImageView 不工作
【发布时间】:2016-05-17 08:55:42
【问题描述】:

我正在尝试使用以下代码从现有视图中删除图像:

-(void) deleteImage:(int)imageID{

//[self.imageArray removeObjectAtIndex:imageID];
//remove the image from the screen
for (UIView* view in self.view.subviews) {
    if ([view isKindOfClass:[UIImageView class]] && [view tag] == imageID) {
        //could be a bug here with the re-Ordering of the array (could add a helper method to reset all the tags on screen when this is called
        NSLog(@"view %@", view);
        //[self.imageArray removeObjectAtIndex:imageID];
        [view removeFromSuperview];
    }
  }
}

NSLog 输出以下内容:

view <UIImageView: 0x18b8d7b0; frame = (0 0; 768 2016); autoresize = RM+BM; userInteractionEnabled = NO; layer = <CALayer: 0x18b8d890>>

我遇到的问题是它似乎正在获取 ImageView 但它没有删除它。

【问题讨论】:

  • 能否请您详细说明一下要求。您真的需要删除imageView 本身还是只清除imageView 显示的图像?
  • @GoGreen 我需要删除 imageView 本身
  • 在从 superView 中删除之前,您已经记录了该语句。尝试在 for 语句之后循环遍历子视图以检查 imageView 是否仍然存在。此外,这不是删除子视图的理想方式。通过将其添加为propertyinstance variable 来保留对要删除的视图的引用。然后,您可以使用此参考将其删除。请再次检查。

标签: ios objective-c xcode uiimageview


【解决方案1】:

由于您尝试修改用户界面,因此您必须在主线程上进行。因此,请执行以下操作:

dispatch_async(dispatch_get_main_queue(), ^{
    [view removeFromSuperview];
});

【讨论】:

    【解决方案2】:

    首先,当您向视图询问其子视图时,您会得到一个子视图数组的副本,因此摆弄该副本数组对您没有任何好处。

    其次,原则上,当您尝试删除子视图时应该会崩溃,因为您使用的是快速枚举,它禁止在枚举中更改集合。

    最后,删除视图的子视图的正确方法是使用 removeFromSuperview 方法,这意味着您确实需要保留对相关图像视图的引用。

    本质上,您应该使用标题为“管理视图层次结构”的 UIView 部分中提供的方法,而不是使用实际的子视图数组本身。这是可能使子视图层次结构进入不一致状态的秘诀。

    【讨论】:

      猜你喜欢
      • 2016-06-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-21
      • 2012-08-13
      • 2015-02-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多