TouchesMoved只获取一次标签文本

时间:2013-11-03 11:33:21

标签: ios uilabel touch-event

我正在制作经典游戏“找一个字” 像这个寻找“狮子”的例子

G H K J L D F G F Y E

J L M N L I O N A D T

G F O I A F E A D G H. ...

我有这段代码来获取所有字母值

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



    }


}}

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

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

你有什么建议吗?

非常感谢你!

2 个答案:

答案 0 :(得分:1)

要做到这一点,你必须保存最后一个字母边界,并检查你是在同一个矩形还是搬走了。

首先,声明一个rect来存储当前的字母。

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



    }


}}

答案 1 :(得分: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:

中清空数组