2011-04-11 133 views
0

嘿,我试图在用户触摸ImageView时更改图像。在ImageView的有像“heart1.png”所以,当我触摸屏幕上的图像浏览器将变为“heart2.png”的时刻,这是我的代码,帮助深表感谢:在TouchesBegan上更改图像

这看起来像
-(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"]; 
    }  
} 
+0

什么可行?什么不?你的问题是什么? – 2011-04-11 13:24:53

+0

不与Xcode相关。 Xcode只是一个IDE – vikingosegundo 2011-04-11 13:43:53

回答

0

一个问题,我:

如果(location.x> = imageView.frame.origin.x & & location.x < = imageView.frame.origin.x + imageView.frame.size - >高度<。 -

应该有宽度:)

0

为什么不通过使用接口构建来放置一个自定义(即,不可见)UIButton在图像上方?然后,您可以将touchesUpInside连接到IBAction方法。那么在你的代码中没有尴尬的陈述,也不会有这样的错误发生。

0

请考虑使用UIButton。

[button setImage:[UIImage imageNamed:@"heart1.png"] forState:UIControlStateNormal]; 
[button setImage:[UIImage imageNamed:@"heart2.png"] forState:UIControlStateHighlighted]; 
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"]]; 
}