user3266053 user3266053 - 6 months ago 15
iOS Question

Add a uiimageview inside a uiview when touching the uivew

What I want to do is when I touch the

, 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
in the
, but that doesn't work).

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)]; = touchLocation;
imageViewFlower.image= [UIImage imageNamed:@"whiteflower.png"];
[GrassView addSubview:imageViewFlower];


Thanks for any help!

ddb ddb

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];