zoukankan      html  css  js  c++  java
  • UIGestureRecognizer在多层视图中的触发问题

    在一个superview中,添加了一个subview。tap一下superview,将subview隐藏起来。
    在视图superview添加一个UITapGestureRecognizer对象,在UITapGestureRecognizer对象的action中实现隐藏subview的逻辑代码。

    UIView *superview = [[UIView alloc] initWithFrame:CGRectMake:(0, 0, 320, 480); 
    UIView *subview = [[UIView alloc] initWithFrame:CGRectMake:(100, 100, 100, 100); 
    UITapGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc] initWithTarget: self action: @selector(handleTap); 
    [superview addGestureRecognizer:recognizer]; 
    [self.view addSubview:superview]; 
    [superview addSubview:subview];

    代码很简单,tap一下superview视图,果然就隐藏了subview。但是,我tap一下subview视图,它也隐藏了subview。

    基于对hitTest:withEvent:调用过程的理解,我们知道hit是在多层view上传递的。

    我想到在subview也加一个UITapGestureRecognizer,将这个tap操作截获,处理掉,这样就不会传到superview上,就不会调用superview上的UITapGestureRecognizer的动作handleTap。

    这个方法虽然能用,但也太笨了,无缘无故做一个操作,还要维护一个方法。笨!!!


    其实,UIGestureRecognizer是有delegate设置的,能对每一个UITapGestureRecognizer的对象进行对应处理。

    - (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{
      CGPoint touchPoint = [touch locationInView:self.view]; 
     return !CGRectContainsPoint(subview.frame, touchPoint); 
     }
     
    完全可以对每一个tap操作touchPoint进行判断,如果touchPoint 在subview上,完全可以返回False,让UIGestureRecognizer不做任何操作,不触发其action。该方法的默认返回值为True。

    记住,recognizer的delegate的属性值要设置为self,才会调用这个方法。
    recognizer.delegate = self;

    在iOS中,很多类都有delegate设置,可以用来实现这类逻辑判断。iOS的架构设计得真的很好,真心赞一句!


     


  • 相关阅读:
    安卓学习-界面-ui-RadioButton CheckBox
    安卓学习-界面-使用点9图制作可拉升图片
    安卓学习-界面-ui-TextEdit
    安卓学习-界面-XML-shap自定义图形
    安卓学习-界面-ui-TextView
    安卓学习-界面-布局-GridLayout
    安卓学习-界面-布局-RelativeLayout
    安卓学习-界面-布局-FrameLayout
    安卓学习-界面-布局-TableLayout
    安卓学习-界面-布局-LinearLayout
  • 原文地址:https://www.cnblogs.com/dyllove98/p/3194338.html
Copyright © 2011-2022 走看看