删除以编程方式添加的UIImageView

时间:2014-06-04 17:30:32

标签: ios objective-c uiimageview

我知道有很多线索关于这个,我读了它们但我无法使它工作。这是我的代码

@property (strong, nonatomic) UIImageView *advertiseView;

- (void)startShowingImage
{
    _advertiseView = [[UIImageView alloc] initWithFrame:CGRectMake(80,320,150,97)];
    _advertiseView.image = [UIImage imageNamed:@"blocksAd.png"];

    [self.view addSubview:_advertiseView];
    NSLog(@"startShowing");
}

- (void)stopShowingImage
{
    NSLog(@"stopShowing");
    [_advertiseView removeFromSuperview];
}

我让NSLogs检查这些方法是否被调用,但是它首先显示的图像永远不会消失。 有关于此的任何建议吗?

2 个答案:

答案 0 :(得分:1)

如果NSLog(@"stopShowing")肯定被调用,那么我认为您可能遇到的唯一问题会导致removeFromSuperview无法正常工作,那就是您没有进行更改(UI更新)主线。

请改为尝试:

[_advertiseView performSelectorOnMainThread:@selector(removeFromSuperview) withObject:nil waitUntilDone:NO];

答案 1 :(得分:0)

检查主线程

中是否调用了addSubview和removeFromSuperView

检查startShowingImage是否只被调用一次,否则你就有了永远无法删除的孤立的UIImageViews

- (void)startShowingImage
{
    if (self.advertiseView) {
        self.advertiseView = [[UIImageView alloc] initWithFrame:CGRectMake(80,320,150,97)];
        self.advertiseView.image = [UIImage imageNamed:@"blocksAd.png"];

        [self.view addSubview:self.advertiseView];
        NSLog(@"startShowing");
    }
}

除非您特别需要避免问题,否则请使用属性语法

相关问题