View transparency and Gesture handling

2019-05-28 09:59发布

问题:

I am currently trying to create a View that would handle all the Gesture that could happened on my application.

I would like this view transparent in order to put other view below and they would still display (I don't want to make them subbiews of the handling view)

The Gesture handling works fine until I set the view color on "clearColor" from then, it is has the view disappear. Unless I stick subviews, in this case the gesture are only happening when hitting on subviews.

My question hence is: How could I manage to have the Gesture event happening on a transparent view?

回答1:

Try something like this. This code adds two subviews to the main view "bottomView which is has a red background and then "testView" which is transparent an overlay on top of "bottomView" with a tap gesture recognizer. If you tap anyway in the "testView" it will print out the NSLog message. I hope that helps.

-(void)viewDidLoad
{
    [super viewDidLoad];

    UIView *bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
    [bottomView setBackgroundColor:[UIColor redColor]];
    [self.view addSubview:bottomView];    
    UIView *testView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 150)];
    [testView setBackgroundColor:[UIColor clearColor]];
    [self.view addSubview:testView];

    UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc] 
                                          initWithTarget:self
                                          action:@selector(handleTap:)];
    [tapRecognizer setNumberOfTapsRequired:1];
    [tapRecognizer setDelegate:testView];
    [testView addGestureRecognizer:tapRecognizer];
}

-(void)handleTap:(UITapGestureRecognizer *)sender 
{
     NSLog(@"Tapped Subview");
}