触摸 uivew 时在 uiview 中添加一个 uiimageview

Add a uiimageview inside a uiview when touching the uivew

我想做的是当我触摸UIView时,我想在触摸的位置添加一个图像。

这是我目前拥有的代码。 (我曾尝试在 CGRectMake 中用 touchLocation 替换 x 和 y,但这不起作用)。

已编辑 清理并重新启动后 xcode 它工作。

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

    }
}

感谢您的帮助!

尝试用以下代码更改if分支中的imageViewFlower插入代码:

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

清理并重新启动后 xcode 代码工作正常。