0
votes

I've a view with 10 character labels (big letters). Each character (label) has a different tag. The functionality that I'm developing is "Trace". When user moves his finger over the view, i want to detect which character is touched. I think I've to implement,

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

But I'm not knowing how to identify touch on the label and identify the character. Can some one help me?

2

2 Answers

1
votes

If you want to know the view that the touch began on (which view the user put their finger down on), you can read any of the touch items returned in the NSSet like so:

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    NSInteger viewTag = [[[touches anyObject] view] tag];
    
    //Check your view using the tags you've set...
}

However, even as the finger moves across the screen, this view property will ONLY return the view initially touched and not the view currently under the finger. To do this, you will need to track the coordinates of the current touch and determine which view it falls into, perhaps like this:

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];

    CGPoint point = [touch locationInView:self.view]; 

    //If all your views are collected as an array
    for(UIView *view in views) {
        if (CGRectContainsPoint([view frame], point))
        {
            //Bingo
        }
    }
}

The key to success on this is to make sure that you are getting your touches in coordinates reference to the proper views, so make sure to call locationInView: and CGRectContainsPoint() appropriately with values that match your application's view hierarchy and where your placing this code (i.e. the View, ViewController, etc.)

0
votes

To detect simple touches you can use UIGestureRecognizer. Read the documentation for more on those. For more complex operations you do need to implement:

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

To identify which item was touched you can give your item's tags values:

myView.tag = 4;

Then just check the tag value of the view reporting the touch and you know which it is.