removeFromSuperview UIImageView无法正常工作

时间:2016-05-17 08:55:42

标签: ios objective-c xcode uiimageview

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

-(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,但它不会删除它。

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:1)

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

其次,原则上,当您尝试删除子视图时,您应该遇到崩溃,因为您正在使用快速枚举,这会禁止在枚举中对集合进行变更。

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

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

相关问题