【问题标题】:iphone - UIView with labels, detect touch when moved fingers on itiphone - 带有标签的 UIView,在其上移动手指时检测触摸
【发布时间】:2011-06-09 14:33:54
【问题描述】:

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

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

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

【问题讨论】:

    标签: iphone touch


    【解决方案1】:

    如果您想知道触摸开始的视图(用户将手指放在哪个视图上),您可以读取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 等)

    希望有帮助!

    【讨论】:

    • 非常感谢您的解决方案。
    【解决方案2】:

    要检测简单的触摸,您可以使用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;
    

    然后只需检查报告触摸的视图的标记值,您就知道它是什么。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-23
      • 2010-11-10
      • 1970-01-01
      相关资源
      最近更新 更多