2015-02-05 37 views
0

所以我創造了這個平移手勢識別器檢測到幾個UIBUttons我聯繫。這個想法是。我正在尋找能夠將我的手指滑過所有按鈕並在觸摸它們時觸發每個按鈕和其中一個按鈕。現在,我可以滑過所有按鈕,並用此代碼觸發聲音。有一個問題正在發生,那就是當我用NSLog語句替換聲音文件時,我用同一個按鈕中的手指進行的每一個微小的小動作都會不斷地重複一遍又一遍,真的很快。它對最輕微的動作做出反應。平移手勢的問題,UIButton的檢測範圍內的輕微運動

如何啓用只聽到聲音一次我的手指觸摸按鈕,並有當我的手指再次觸摸相同的按鈕再次播放同樣的聲音的能力之後。當你在真正的鋼琴上觸摸或滑動手指時,獲得的效果幾乎相同。

誰能幫我這個?

- (void)viewDidLoad 
{ 
[super viewDidLoad]; 

UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePanGesture:)]; 

[self.view addGestureRecognizer:pan]; 
} 




//Method to handle the pan: 



-(void)handlePanGesture:(UIPanGestureRecognizer *)gesture 
{ 
//create a CGpoint so you know where you are touching 
CGPoint touchPoint = [gesture locationInView:self.view]; 

//just to show you where you are touching... 
NSLog(@"%@", NSStringFromCGPoint(touchPoint)); 

//check your button frame's individually to see if you are touching inside it 
if (CGRectContainsPoint(self.button1.frame, touchPoint)) 
{ 
    NSLog(@"you're panning button1"); 
} 
else if(CGRectContainsPoint(self.button2.frame, touchPoint)) 
{ 
    NSLog(@"you're panning button2"); 
} 
else if (CGRectContainsPoint(self.button3.frame, touchPoint)) 
{ 
    NSLog(@"you're panning button3"); 
} 

回答

1

保持一個NSMutableArray對於這聽起來已經自上次觸及事件起到檢測(僞代碼如下,請更換採用適當的方法名和簽名):

NSMutableArray *myPlayedSounds; 
void touchDown:(UITouch *) touch 
{ 
    //Empty played sounds list as soon as a touch event is sensed 
    [myPlayedSounds removeAllObjects]; 
} 

-(void)handlePanGesture:(UIPanGestureRecognizer *)gesture 
{ 
//create a CGpoint so you know where you are touching 
CGPoint touchPoint = [gesture locationInView:self.view]; 

//just to show you where you are touching... 
NSLog(@"%@", NSStringFromCGPoint(touchPoint)); 

//check your button frame's individually to see if you are touching inside it 
if (CGRectContainsPoint(self.button1.frame, touchPoint) && [myPlayedSounds containsObject:@"button1"] == NO) 
{ 
    NSLog(@"you're panning button1"); 
    [myPlayedSounds addObject:@"button1"]; 
} 
else if(CGRectContainsPoint(self.button2.frame, touchPoint) && [myPlayedSounds containsObject:@"button2"] == NO) 
{ 
    NSLog(@"you're panning button2"); 
    [myPlayedSounds addObject:@"button2"]; 

} 
else if (CGRectContainsPoint(self.button3.frame, touchPoint) && [myPlayedSounds containsObject:@"button3"] == NO) 
{ 
    NSLog(@"you're panning button3"); 
    [myPlayedSounds addObject:@"button3"]; 
} 
} 
+0

感謝ABHashmi!這開始有意義!該陣列仍撲朔迷離我在這一點上,如,你指的是實際的button1,2,3或者你調用「聲音文件」名爲「button1,2,3」被假設是在下面的按鈕。該項目(我的聲音叫不同,只是想明白我明白)等?因爲button1,2,3在這一點上只是IBOutlets,並且在它們中沒有IBActions,只是想確保我理解正確。 – 2015-02-05 19:26:59

+0

@MilesH。這可能有助於通過這個[教程](http://rypress.com/tutorials/objective-c/data-types/nsarray) – CaptJak 2015-02-05 19:30:09

+0

萬里,數組只是爲了跟蹤哪些聲音已經被播放。它可以是您爲每個按鈕選擇的任何字符串或NSNumber值。我的意思是,如果button1被按下,我可以添加字符串@「喲」,但這也意味着我將檢查數組中是否存在@「yo」。 簡單地說: 一)值存在:==>聲音已被播放。 b)值不存在:==>聲音尚未播放。另外,無論何時我選擇播放聲音,我都會將相應的值添加到陣列中,從而有效地將聲音標記爲已播放。 – 2015-02-05 19:30:45