user3266053 user3266053 - 3 months ago 7
iOS Question

Add a uiimageview inside a uiview when touching the uivew

What I want to do is when I touch the

UIView
, I want to add an image at the touched location.

This is my code I have for the moment.
(I have tried to replace x and y with
touchLocation
in the
CGRectMake
, but that doesn't work).

Edited
After clean and restart xcode it work.

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

UITouch *touch = [touches anyObject];
CGPoint touchLocation = [touch locationInView:touch.view];

if ([touch view] == GrassView) {

NSLog(@"Hit grass");

UIImageView *imageViewFlower =[[UIImageView alloc] initWithFrame:CGRectMake(0,0,50,50)];
imageViewFlower.center = touchLocation;
imageViewFlower.image= [UIImage imageNamed:@"whiteflower.png"];
[GrassView addSubview:imageViewFlower];

}
}


Thanks for any help!

ddb ddb
Answer

try to change the imageViewFlower insertion code in the if branch with the following code:

UIImageView *imageViewFlower =[[UIImageView alloc] initWithFrame:CGRectMake(touchLocation.x-25,touchLocation.y-25,50,50)];
imageViewFlower.image = [UIImage imageNamed:@"whiteflower.png"];
[GrassView addSubview:imageViewFlower];
Comments