在TouchesBegan上更改图像

时间:2011-04-11 13:22:15

标签: iphone cocoa-touch ios uiimageview

嘿,我正在尝试在用户触摸ImageView时更改图像。目前ImageView的图像为“heart1.png”,所以当我触摸屏幕上的ImageViewer时,它将变为“heart2.png”这是我的代码,非常感谢帮助:

-(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [[event allTouches] anyObject];
    CGPoint location = [touch locationInView:self.view];
    if (location.x >= imageView.frame.origin.x && location.x <= imageView.frame.origin.x + imageView.frame.size.height && location.y >= imageView.frame.origin.y && location.y <= imageView.frame.origin.y + imageView.frame.size.height) {
        imageView.image = [UIImage imageNamed:@"heart2.png"];
    }    
}

4 个答案:

答案 0 :(得分:0)

这对我来说似乎是一个问题:

if(location.x&gt; = imageView.frame.origin.x&amp;&amp; location.x&lt; = imageView.frame.origin.x + imageView.frame.size。 - &gt; height &LT; -

可能是宽度:)

答案 1 :(得分:0)

为什么不通过使用界面构建在图像上放置自定义(即不可见)UIButton来简化事情,而不是愚弄检查边界矩形的坐标?然后,您可以将touchesUpInside连接到IBAction方法。然后你的代码中没有尴尬的if语句,也不会有这样的错误发生的机会。

答案 2 :(得分:0)

请考虑使用UIButton。

[button setImage:[UIImage imageNamed:@"heart1.png"] forState:UIControlStateNormal];
[button setImage:[UIImage imageNamed:@"heart2.png"] forState:UIControlStateHighlighted];

答案 3 :(得分:0)

无需查找view的位置,您无需移动UIImageView。只需这样做:

-(void)viewDidLoad 
{
    // imageView is your UIImageView
    imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0.0, 0.0, 320.0, 480.0)];
    [imageView setImage:[UIImage imageNamed:@"heart1.png"]];
    [imageView setUserInteractionEnabled:YES];

    // Make sure userInteractionEnable is set to be YES; otherwise the touch event will be happen on UIView not on ImageView;
   [self.view addSubview:imageView];
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
{
    UITouch *touch = [[event allTouches]anyObject];
    if([touch view]==imageView)
        [imageView setImage:[UIImage imageNamed:@"heart2.png"]];
}