2 for 2012 for_2012 于 2013.05.20 16:07 提问

IOS-移除imageView

屏幕上有一张图片需要在停留的时候全屏。

    UILongPressGestureRecognizer *hold = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(hold:)];
    hold.minimumPressDuration = 0;

    [self.photoImageView addGestureRecognizer:hold];

监听器:

-(void)hold:(UILongPressGestureRecognizer *)sender{
    UIImageView *img = [[UIImageView alloc] initWithImage:self.photo];
    img.userInteractionEnabled = NO;

    if(sender.state == UIGestureRecognizerStateBegan){
        NSLog(@"state began");
        [self.view addSubview:img];
    } else if (sender.state == UIGestureRecognizerStateEnded){
        NSLog(@"state ended");
        [img removeFromSuperview];
    }
}

图片成功添加到屏幕中,只有 [img removeFromSuperview]好像没有响应。

结束状态的NSlog也正常。

3个回答

KindAzrael
KindAzrael   2013.05.20 23:53
已采纳
-(void)hold:(UILongPressGestureRecognizer *)sender{
    //每次响应函数 img都是一个新alloc出来的UIImageView
    UIImageView *img = [[UIImageView alloc] initWithImage:self.photo];
    img.userInteractionEnabled = NO;

    if(sender.state == UIGestureRecognizerStateBegan){
        NSLog(@"state began");
        //添加新alloc出来的UIImageView,可以看到界面效果
        [self.view addSubview:img];
    } else if (sender.state == UIGestureRecognizerStateEnded){
        NSLog(@"state ended");
       //remove 新alloc出来的UIImageView当然没有效果,它还没有被add进去
        [img removeFromSuperview];
    }
}

改成这样

-(void)hold:(UILongPressGestureRecognizer *)sender{
    if(sender.state == UIGestureRecognizerStateBegan){
        NSLog(@"state began");
        UIImageView *img = [[UIImageView alloc] initWithImage:self.photo];
        img.userInteractionEnabled = NO;
        img.tag = kTAG_PHOTO_IMAGE_VIEW
        [self.view addSubview:img];
    } else if (sender.state == UIGestureRecognizerStateEnded){
        NSLog(@"state ended");
        UIImageView *img = (UIImageView *)[self.view viewWithTag:kTAG_PHOTO_IMAGE_VIEW];
        [img removeFromSuperview];
    }
}
xiaoyaokk
xiaoyaokk   2013.05.20 16:28

结束时又初始化了一个新的UIImageView,对新的UIImageView执行removeFromSuperview,所以之前添加的UIImageView并没有被移除掉,可以给UIImageView设置一个tag值,结束时先通过tag值取到UIImageView,再执行removeFromSuperview。

lwq421336220
lwq421336220   2013.05.22 14:25

设置UIImageView *img为全局变量就ok了

Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!