【发布时间】:2012-07-30 01:10:16
【问题描述】:
您好,我有一个问题,我几天都想不通。我有一个 touchesBegan 方法,我想用它来判断何时有人点击 UIImageView,以便它可以使用 NSTimers 上下移动不同的 UIImageView。出于某种原因,我的 TouchesBegan 无法工作,我知道这是问题所在,因为我使用 NSLogs 进行了测试,结果表明该方法没有被调用。这是我的代码,谢谢 附言如果有一个超级快速的修复,它让我看起来很愚蠢,我很抱歉我现在只开发了 6 天。
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
CGPoint pt = [[touches anyObject] locationInView:self.view];
if (CGRectContainsPoint(flyImageButton.frame, pt)) {
flying = YES;
[playerFall invalidate];
playerFlyUp = [NSTimer scheduledTimerWithTimeInterval:.03 target:self selector:@selector(flyUp) userInfo:nil repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:playerFlyUp forMode:NSRunLoopCommonModes];
}
}
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
if (flying == YES) {
flying = NO;
[playerFlyUp invalidate];
[self startFallTimer];
}
}
这是我的 .h 文件,供询问的人使用...
#import <UIKit/UIKit.h>
@interface GameViewController : UIViewController {
IBOutlet UILabel *scoreLabel, *coinsLabel;
IBOutlet UIImageView *flyImageButton, *playerImage, *flyingObject;
IBOutlet UIScrollView *scroll;
int score;
int coins;
BOOL flying;
NSTimer *playerFlyUp, *playerFall, *scoreTimer, *coinsTimer;
}
@end
我也试过这样的 UITouch...
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
//CGPoint pt = [[touches anyObject] locationInView:self.view];
UITouch *touch = [[event allTouches]anyObject];
//if (CGRectContainsPoint(flyImageButton.frame, pt)) {
if ([touch view] == flyImageButton) {
flying = YES;
[playerFall invalidate];
playerFlyUp = [NSTimer scheduledTimerWithTimeInterval:.03 target:self selector:@selector(flyUp) userInfo:nil repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:playerFlyUp forMode:NSRunLoopCommonModes];
}
}
让我真正感到困惑的是 NSLog "Pos 1" 是如何从不触发的,无论我在哪里触摸......
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
//CGPoint pt = [[touches anyObject] locationInView:self.view];
UITouch *touch = [[event allTouches]anyObject];
CGPoint loc = [touch locationInView:self.view];
//This NSLog never displays leading me to think that my CGPoint isn't the issue...
NSLog(@"Pos 1");
if (CGRectContainsPoint(flyImageButton.frame, loc)) {
//if ([touch view] == flyImageButton) {
NSLog(@"Pos 2");
flying = YES;
[playerFall invalidate];
playerFlyUp = [NSTimer scheduledTimerWithTimeInterval:.03 target:self selector:@selector(flyUp) userInfo:nil repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:playerFlyUp forMode:NSRunLoopCommonModes];
}
}
【问题讨论】:
-
我们可以看看你的.h文件吗
-
你确定你没有什么东西吃掉你的触摸(例如你的视图顶部的按钮)?此外,如果您计划执行自定义触摸处理,则应根据苹果指南覆盖所有 4 种触摸方法。
-
UIScrollView 会干扰它吗?我有一个触发 touchesBegan 的按钮,但它应该在滚动视图上执行某些操作
标签: objective-c ios xcode touchesbegan