在 TouchesBegan 上更改图像
嘿,我试图在用户触摸 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"];
}
}
Hey, I am trying to change the image when the user touches the ImageView. At the moment the ImageView has the image "heart1.png" so when i touch the ImageViewer on screen it will change to "heart2.png" this is my code, help is much appreciated:
-(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"];
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这对我来说似乎是个问题:
if (location.x >= imageView.frame.origin.x && location.x <= imageView.frame.origin.x + imageView.frame.size. --> 高度 <--
可能应该是宽度:)
That looks like a problem to me:
if (location.x >= imageView.frame.origin.x && location.x <= imageView.frame.origin.x + imageView.frame.size.--> height <--
should be width there probably :)
与其胡乱检查边界矩形的坐标,为什么不通过使用界面构建在图像上放置一个自定义(即不可见)UIButton 来简化事情呢?然后,您可以将
touchesUpInside
连接到 IBAction 方法。这样你的代码中就不会出现尴尬的 if 语句,并且犯这样的错误的可能性也会减少。Rather than fool around with checking coordinates against a bounding rect, why don't you simplify things by using interface building to place a custom (i.e. invisible) UIButton right over the image? Then you can hook up
touchesUpInside
to an IBAction method. Then there's no awkward if statements in your code and less chance of making mistakes like this.考虑使用 UIButton 代替。
Consider using an UIButton instead.
不需要找到
view
的位置,也不需要移动UIImageView
。只需这样做:There is no need to find location of
view
, You don't have to do moveUIImageView
. Simply do this: