Search code examples
iosobjective-cuiviewtapinteraction

How to disable Tap gesture (all interaction) in UIView and its subviews?


I have 2 classes cellView(basically a cell with tap) and Board view With 64 cellViews. From my VC i want to disable/enable all interactions on them on certain event. this is my code.

if(currentGame.isYourTurn==NO){
    [divBoardView  setUserInteractionEnabled:NO];
    for(UIView*currentView in  [divBoardView  subviews]){
        [currentView  setUserInteractionEnabled:NO];
    }
} else ..

and in cell view is just view with

UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc]
   initWithTarget:self action:@selector(cellTapped)];
[self addGestureRecognizer:tapRecognizer];

I want to disable and enable interaction without adding and deleting tapGestureRecognisers.


Solution

  • There's no need to iterate [divBoardView subviews] and set each one's userInteractionEnabled property. Simply setting this property on the parent view, in this case divBoardView will disable interaction for all subviews.

    With that being said, the UITapGestureRecognizer should not be attached to divBoardView or any view that you're planning on disabling, as it will not fire if userInteractionEnabled is set to NO.

    Depending on your design, it may be better to attach the gesture recognizer to your viewController's view property:

    // Where self is the view controller
    [self.view addGestureRecognizer:tapRecognizer];
    

    And process interaction based on some state:

    @interface YourViewController ()
    
    @property (assign, nonatomic) BOOL isBoardActive;
    
    @end
    
    
    
    @implementation 
    
    - (void)handlerTap:(UITapGestureRecognizer *)tap {
    
        UIView *viewControllerView = tap.view.
        CGPoint location           = [tap locationInView:viewControllerView];
    
        if (_isBoardActive && CGRectContainsPoint(_boardView.frame, location)) {
            // Process tap on board   
        } else {
            // Process tap elsewhere
        }
    }
    
    @end
    

    This is just one solution. It is difficult to recommend the ideal solution as there is very little information provided with regards to your problem. There are many more ways of accomplishing the same thing and the best alternative will depending on your current app structure, design, etc.