-1

我正在开发一款经典游戏“find a word”,比如这个寻找“lion”的例子

GHKJLDFGFYE

JLMN狮子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);



    }


}}

它运行良好,因为当我用手指触摸它们时,它会正确获取标签文本。我的问题是我只需要获得一次价值......

现在它会多次获取该值,直到您传递给另一个字母

你有什么建议吗?

太感谢了!!

4

2 回答 2

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);
        }



    }


}}
于 2013-11-03T11:55:28.300 回答
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:

于 2013-11-03T11:58:47.340 回答