UIView带有标签,当手指在上面移动时检测触摸



我有一个包含10个字符标签(大写字母)的视图。每个字符(标签)都有不同的标签。我正在开发的功能是"跟踪"。当用户在视图上移动手指时,我想检测哪个字符被触摸了。我想我必须实施

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

但我不知道如何识别标签上的触摸和字符。有人能帮我吗?

如果您想知道触摸开始的视图(用户将手指放在哪个视图上),您可以读取NSSet中返回的任何触摸项,如下所示:

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

但是,即使手指在屏幕上移动,此view属性也只会返回最初触摸的视图,而不会返回手指下的当前视图。要做到这一点,你需要跟踪当前触摸的坐标,并确定它属于哪个视图,可能是这样的:

- (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
        }
    }
}

在这方面取得成功的关键是确保您在坐标系中接触到正确的视图,因此请确保使用与应用程序的视图层次结构匹配的值适当地调用locationInView:CGRectContainsPoint(),以及放置此代码的位置(即view、ViewController等)

要检测简单的触摸,可以使用UIGestureRecognizer。阅读相关文档了解更多信息。对于更复杂的操作,您确实需要实现:

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

要识别被触摸的物品,您可以给物品的标签值:

myView.tag = 4;

然后只需检查报告触摸的视图的标记值,就可以知道是哪一个。

最新更新