触摸uivew时,在uiview中添加uiimageview

时间:2016-08-25 10:01:23

标签: ios objective-c uiview uiimageview uitouch

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

这是我目前的代码。 (我试图用touchLocation中的CGRectMake替换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];

    }
}

感谢您的帮助!

2 个答案:

答案 0 :(得分:1)

尝试使用以下代码更改if分支中的UIImageView *imageViewFlower =[[UIImageView alloc] initWithFrame:CGRectMake(touchLocation.x-25,touchLocation.y-25,50,50)]; imageViewFlower.image = [UIImage imageNamed:@"whiteflower.png"]; [GrassView addSubview:imageViewFlower]; 插入代码:

interface{}

答案 1 :(得分:0)

清理并重启xcode后,代码运行正常。