CristiC
CristiC

Reputation: 22698

remove UIImageView from its Superview

In my application when the user touches the screen, I put an UIImageView on the screen like this:

- (void) drawPoint:(CGPoint) toLocation {
    UIImageView *image = [[UIImageView alloc] initWithFrame:CGRectMake(toLocation.x, toLocation.y, SIZE_X, SIZE_Y)];
    image.tag = 1;
    [image setImage:[UIImage imageNamed:@"point.png"]];
    [self.myView addSubview:image];
    [image release];
}

Here MyView is an UIView.

When the user has finished touching, I want to remove my UIImageView. I have tried this:

- (void) removeFromPoint:(CGPoint) location{
    UIImageView *image;
    [[image viewWithTag:1] removeFromSuperview];
}

or

- (void) removeFromPoint:(CGPoint) location{
    UIImageView *image = (UIImageView *)[self.MyView viewWithTag:1];
    [image removeFromSuperview];
}

but both of them end up in EXC_BAD_ACCESS. Do you know how can I accomplish this?

Thanks.

Upvotes: 1

Views: 8965

Answers (2)

Piotr Czapla
Piotr Czapla

Reputation: 26532

If you want to remove uimage under the touch try this:

UIView * imageView = [self.myView hitTest:location withEvent:nil];
if ([imageView isKindOfClass:[UIImageView class]] && imageView.tag == 1) {
   [imageView removeFromSuperview];
}

(note I've typed it here, i haven't test that code)

If you wish to debug your code enable NSZombies and check why you gets the bad_access. (check this to learn more about NSZombieEnabled http://www.cocoadev.com/index.pl?NSZombieEnabled)

If you are going to add only one view. Then I would store it in a retained property and I would add/remove it on events like this:

@property (nonatomic,retain) UIImageView* marker;

@interface
@syntesize marker;

-(void) onTouchDown {
    [self.view addSubview:marker];
}

-(void) onTouchUp {
    [marker removeFromSuperview];
}

Upvotes: 1

Aliaksandr Bialiauski
Aliaksandr Bialiauski

Reputation: 1590

The first example of removing image view is wrong. In the second one what is POINT_TAG equal to? Try to use tag greater then 9. Try to debug what UIImageView *image = (UIImageView *)[self.MyView viewWithTag:POINT_TAG]; returns.

Upvotes: 1

Related Questions