【问题标题】:how to detect event touch in subview or how to make parent view was touched when we touch subview?如何检测子视图中的事件触摸或当我们触摸子视图时如何使父视图被触摸?
【发布时间】:2011-08-02 05:32:47
【问题描述】:

我有 2 个 UIView。

第一个是父视图

第二个是子视图,

我们如何检测子视图何时被触摸?

或者我想在用户触摸子视图时触摸父视图,任何代码可以帮助我做到这一点?可以这样做吗?

因为我有一个Something Function,当其中一个被触摸时会调用它。

【问题讨论】:

    标签: iphone xcode uiview subview


    【解决方案1】:

    这对我有用:

    (链接xib或storyboard中的子视图)

    ViewController.h

    @interface ViewController : UIViewController
    
    @property (nonatomic, strong) IBOutlet UIView *subview;
    @property (nonatomic, strong) UITapGestureRecognizer *tapRecognizer;
    
    @end
    

    ViewController.m

    @implementation ViewController
    
    @synthesize subview;
    @synthesize tapRecognizer;
    
    - (void)viewDidLoad
    {
        [super viewDidLoad];
        // Do any additional setup after loading the view, typically from a nib.
    
        tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self
                                                                action:@selector(handleTap:)];   
    
        [subview addGestureRecognizer:tapRecognizer];
    }
    
    - (IBAction)handleTap:(UITapGestureRecognizer *)recognizer {
        if (recognizer.state == UIGestureRecognizerStateEnded){
            //code here
            NSLog(@"subview touched");
        }
    }
    
    @end
    

    【讨论】:

    • 在handleTap函数中,我添加了以下行来隐藏键盘。 [self.view endEditing:YES];
    【解决方案2】:

    问题已解决。我认为有人给出了很好的答案,但我忘记了。

    这就是我所做的。 XIB中有一个选项。有一个复选框(标题为“启用用户交互”)指定子视图是否处理用户事件。

    取消选中复选框,所有对子视图的触摸都转到父视图或它后面的任何其他视图。

    【讨论】:

    • 那个复选框叫什么名字?
    • 我不再为 iPhone 编写代码,但我已经忘记了。我认为这是 UIControl 和 UIView 之间的主要区别。 UIControl 默认启用该复选框。
    【解决方案3】:

    要检测触摸事件,您需要在子视图或超级视图中添加UITapGestureRecognizer(您希望在其中获得触摸)。

    - (void)viewDidLoad
    {
        UITapGestureRecognizer* tap = [[UITapGestureRecognizer alloc] initWithTarget:self
                                                                        action:@selector(tap:)];
            tap.numberOfTapsRequired = 1;
    
            [self addGestureRecognizer:tap];
    
    
        [super viewDidLoad];
    }
    

    那么你可以添加UITapGestureRecognizer的委托方法

    - (void) touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event
    {
         UITouch *touch = [touches anyObject]; 
         // here you can get your touch
         NSLog(@"Touched view  %@",[touch.view class] );
    }
    

    希望它能给你一些想法..

    【讨论】:

      【解决方案4】:

      这可能会有所帮助:

      UITouch *touch = [event.allTouches anyObject];
      CGPoint touchPoint = [touch locationInView:YOUR VIEW NAME];
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多