2011-03-08 114 views
2

我是新来iPhone编程。 我正在试图做一个简单的窗口与一个猫做两个声音。当你点击猫图标时,它应该做“miaau”,当你拖过窗口(中风)时,它应该使“mrrrr”。 它的工作原理,但总是当我尝试使猫mrrrrr功能TouchesBegan火灾和猫也做“miaaau”。Touchesbegan使用touchesmoved时总是会触发?

如何使界面识别我只想要中风猫,而不是为了做第一个选项而触摸它,“miaau”?

回答

7

我建议添加的NSTimer到的touchesBegan方法与小的时间间隔(比如0.1秒):

BOOL tap_event = NO; //ivar declared in header 

-(void) touchesBegan:... { 
    tap_event = YES; 
    [NSTimer scheduledTimerWithTimeInterval: 0.1 target: self selector: @selector(checkTap:) userInfo: nil repeats: NO]; 
} 

-(void) checkTap:(NSTimer*) t { 
    if(tap_event) //miauu here 
    tap_event = NO; 
} 

-(void) touchesMoved:... { 
    tap_event = NO; 
    //mrrrr here 
} 

或者作为UIGestureRecognizers的选项检查文档

+0

好吧,我会尝试用BOOL的,让你知道我的作品。非常感谢。 – Rafal 2011-03-08 07:08:54

+0

+1它肯定会工作。 – Ishu 2011-03-08 07:10:00

+0

如果你不想担心计时器,你也可以使用[self performSelector:@selector(checkTap)withObject:nil afterDelay:0.1]。 – bornbnid 2011-08-30 15:00:01

0

Max' solution是正确的。它一定会奏效。我有另一种选择,请参阅此方法。

将您的播放器对象放在.h文件中,然后在viewDidLoad中进行分配并释放到dealloc中。

-(void) touchesBegan:... { 

    //Play the miauu sound. 
} 

-(void) touchesMoved:... { 
[self.yourPlayer stop]; 

    //Play mrrrr. 
} 

编辑

.h文件中,

AVAudioPlayer *avPlayer1; 
AVAudioPlayer *avPlayer2; 

.m文件

-(void) touchesBegan:... { 
    NSString *path = [[NSBundle mainBundle] pathForResource:@"cat" ofType:@"wav"]; 
    avPlayer1 = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL]; 
    [avPlayer1 play]; 
} 

-(void) touchesMoved:... { 
    [avPlayer1 stop]; 
    NSString *path = [[NSBundle mainBundle] pathForResource:@"cat" ofType:@"wav"]; 
    avPlayer2 = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL]; 
    [avPlayer2 play]; 
} 

-(void)dealloc 
{ 
    [avPlayer1 release]; 
    [avPlayer2 release]; 
    [super dealloc]; 
} 
+0

最大的解决方案。猫使得miauu当点击mrrrr当冲程但我有问题: - (无效)checkKlik:(的NSTimer *)吨{ \t如果(的点击){ \t \t如果([触摸视图] ==果德){ \t \t \t NSString * path = [[NSBundle mainBundle] pathForResource:@“cat”ofType:@“wav”]; AVAudioPlayer * theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL]; \t \t \t [theAudio play]; \t \t} \t \t klik = NO; \t} } 它表明我没有声明触摸。 因为我只想点击“KOT”视图,所以我需要使用触摸视图kot进行IF。 – Rafal 2011-03-08 07:58:05

+0

因为你让你的功能和触摸是touchesBegan和touchesMoved method.ok的一部分,请尝试我的答案它可以帮助你。 – Ishu 2011-03-08 08:26:46

+0

Ishu,当我让你的答案如何显示在touchesMoved米奥猫正在播放和停止它? – Rafal 2011-03-08 08:43:04

相关问题