2013-11-03 15 views
-1

我工作的一個經典遊戲 「找一個字」 像這樣的例子在尋找 「獅子」TouchesMoved獲取標籤文本只有一次

GHKJLDFGFYE

JLMN LION ADT

GFOIAFEADGH ...

我有這段代碼得到所有的字母值

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{ 

[self touchesBegan:touches withEvent:event]; 
UITouch *touch = [[event allTouches] anyObject]; 

CGPoint touchPoint = [[touches anyObject] locationInView:allLetters]; 
for (UILabel *letter in self.lettersArray) { 


    if (touchPoint.x > letter.frame.origin.x && 
     touchPoint.x < letter.frame.origin.x + letter.frame.size.width && 
     touchPoint.y > letter.frame.origin.y && 
     touchPoint.y < letter.frame.origin.y + letter.frame.size.height) 
    { 

     [letter setBackgroundColor:[UIColor redColor]]; 
     NSLog(@"%@",letter.text); 



    } 


}} 

它運行良好,因爲它正確地獲取標籤文本時,我用手指觸摸它們。我的問題是我需要的價值只有一次......

現在得到值很多很多次,直到你傳遞給另一個字母

你有什麼建議嗎?

非常感謝你!

回答

1

要做到這一點,你必須保存最後的字母邊界,並檢查你是否在同一矩形或移動。

首先,聲明一個存儲當前字母的矩形。

CGRect lastLetter;

然後修改你的方法按如下:

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{ 

[self touchesBegan:touches withEvent:event]; 
UITouch *touch = [[event allTouches] anyObject]; 

CGPoint touchPoint = [[touches anyObject] locationInView:allLetters]; 
for (UILabel *letter in self.lettersArray) { 


    if (touchPoint.x > letter.frame.origin.x && 
     touchPoint.x < letter.frame.origin.x + letter.frame.size.width && 
     touchPoint.y > letter.frame.origin.y && 
     touchPoint.y < letter.frame.origin.y + letter.frame.size.height) 
    { 

     [letter setBackgroundColor:[UIColor redColor]]; 
     if(letter.frame.origin.x != lastLetter.origin.x) 
     { 
      lastLetter = letter.frame; 
      NSLog(@"%@",letter.text); 
     } 



    } 


}} 
+0

哇!謝謝老兄!這是完美的...我只是爲Y添加if語句 –

0

您可以創建一個存儲所有感動標籤的數組,像這樣:

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{ 

    if(!_touchedLetters) // create the array if it doesn't exists 
     _touchedLetters = [[NSMutableArray alloc] init]; 

    [self touchesBegan:touches withEvent:event]; 
    UITouch *touch = [[event allTouches] anyObject]; 

    CGPoint touchPoint = [[touches anyObject] locationInView:allLetters]; 
    for (UILabel *letter in self.lettersArray) { 

    if([_touchedLetters containsObject:letter]) //continue if it already been added 
     continue; 

    if (touchPoint.x > letter.frame.origin.x && 
     touchPoint.x < letter.frame.origin.x + letter.frame.size.width && 
     touchPoint.y > letter.frame.origin.y && 
     touchPoint.y < letter.frame.origin.y + letter.frame.size.height) 
    { 

     [letter setBackgroundColor:[UIColor redColor]]; 
     NSLog(@"%@",letter.text); 

     [_touchedLetters addObject:letter] 
    } 
}} 

然後你可以空數組在 - (void)touchesEnded:withEvent: