user3266053 user3266053 - 1 year ago 59
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
Answer Source

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];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download