MusiGenesis
MusiGenesis

Reputation: 75296

How to disable touch input to all views except the top-most view?

I have a view with multiple subviews. When a user taps a subview, the subview expands in size to cover most of the screen, but some of the other subviews are still visible underneath.

I want my app to ignore touches on the other subviews when one of the subviews is "expanded" like this. Is there a simple way to achieve this? I can write code to handle this, but I was hoping there's a simpler built-in way.

Upvotes: 49

Views: 86479

Answers (12)

SmileBot
SmileBot

Reputation: 19642

Simple solution. Add a dummy gesture that does nothing. Make it reusable by adding it to an extension like this:

extension UIView {
    func addNullGesture() {
        let gesture = UITapGestureRecognizer(target: self,
                                             action: #selector(nullGesture))
        addGestureRecognizer(gesture)
    }
    
    @objc private func nullGesture() {}
}

Upvotes: 0

Bogdan Razvan
Bogdan Razvan

Reputation: 1714

In Swift 5, I achieved this behaviour by placing a view right on top(the highlighted one) and setting:

myView.isUserInteractionEnabled = true

This does not let the touches go through it, thus ignoring the taps.

enter image description here

Upvotes: 1

Robert Atkins
Robert Atkins

Reputation: 24668

Add a TapGestureRecognizer to your "background view" (the translucent one which "grays out" your normal interface) and set it to "Cancels Touches In View", without adding an action.

let captureTaps = UITapGestureRecognizer()
captureTaps.cancelsTouchesInView = true
dimmedOverlay?.addGestureRecognizer(captureTaps)

Upvotes: 5

Werner Kratochwil
Werner Kratochwil

Reputation: 382

I had the same problem, but the above solutions did not help. I then noticed that calling super.touchesBegan(...) was the problem. After removing this the event was only handled by the top-most view.

I hope this is of help to anybody.

Upvotes: -1

musixlemon
musixlemon

Reputation: 61

Just parentView.UserInteractionEnabled = NO will do the work. Parent view will disable user interaction on all the view's subviews. But enable it does not enable all subviews(by default UIImageView is not interactable). So an easy way is find the parent view and use the code above, and there is no need to iterate all subviews to perform a selector.

Upvotes: 5

Krishnabhadra
Krishnabhadra

Reputation: 34275

Hope this help...

[[yourSuperView subviews]
   makeObjectsPerformSelector:@selector(setUserInteractionEnabled:)
   withObject:[NSNumber numberWithBool:FALSE]];

which will disable userInteraction of a view's immediate subviews..Then give userInteraction to the only view you wanted

yourTouchableView.setUserInteraction = TRUE;

EDIT:

It seems in iOS disabling userInteraction on a parent view doesn't disable userInteraction on its childs.. So the code above (I mean the one with makeObjectsPerformSelector:)will only work to disable userInteraction of a parent's immediate subviews..

See user madewulf's answer which recursively get all subviews and disable user interaction of all of them. Or if you need to disable userInteraction of this view in many places in the project, You can categorize UIView to add that feature.. Something like this will do..

@interface UIView (UserInteractionFeatures)
-(void)setRecursiveUserInteraction:(BOOL)value;
@end

@implementation UIView(UserInteractionFeatures)
-(void)setRecursiveUserInteraction:(BOOL)value{
    self.userInteractionEnabled =   value;
    for (UIView *view in [self subviews]) {
        [view setRecursiveUserInteraction:value];
    }
}
@end

Now you can call

[yourSuperView setRecursiveUserInteraction:NO];

Also user @lxt's suggestion of adding an invisible view on top of all view's is one other way of doing it..

Upvotes: 57

JPetric
JPetric

Reputation: 3918

I would do this by putting a custom transparent button with the same frame as the superView. And then on top of that button I would put view that should accept user touches. Button will swallow all touches and views behind it wouldn't receive any touch events, but view on top of the button will receive touches normally.

Something like this:

- (void)disableTouchesOnView:(UIView *)view {
    UIButton *ghostButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, view.frame.size.width, view.frame.size.height)];
    [ghostButton setBackgroundColor:[UIColor clearColor]];
    ghostButton.tag = 42; // Any random number. Use #define to avoid putting numbers in code.

    [view addSubview:ghostButton];
}

And a method for enabling the parentView.

- (void)enableTouchesOnView:(UIView *)view {
    [[view viewWithTag:42] removeFromSuperview];
}

So, to disable all views in the parentViev behind yourView, I would do this:

YourView *yourView = [[YourView alloc] initWithCustomInitializer];
// It is important to disable touches on the parent view before adding the top most view.
[self disableTouchesOnView:parentView];
[parentView addSubview:yourView];

Upvotes: 6

tianwalker
tianwalker

Reputation: 21

I will give my 2 cents to this problem. Iteratively run userInteractionEnabled = false it's one way. Another way will be add a UIView like following.

EZEventEater.h

#import <UIKit/UIKit.h>
@interface EZEventEater : UIView
@end

EZEventEater.m

#import "EZEventEater.h"
@implementation EZEventEater

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        self.backgroundColor = [UIColor clearColor];
        self.userInteractionEnabled = false;
    }
    return self;
}


- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
   //EZDEBUG(@"eater touched");
}

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

}

- (void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{

}

In your code you add the EZEventEater view to cover all the views that your may block the touch event. Whenever you want to block the touch event to those views, simply call

eater.userInteractionEnabled = YES;

Hope this helpful.

Upvotes: 2

Chris Prince
Chris Prince

Reputation: 7574

For my app, I think it will be sufficient to disable navigation to other tabs of the app (for a limited duration, while I'm doing some processing):

self.tabBarController.view.userInteractionEnabled = NO;

Also, I disabled the current view controller--

self.view.userInteractionEnabled = NO;

(And, by the way, the recursive solutions proposed here had odd effects in my app. The disable seems to work fine, but the re-enable has odd effects-- some of the UI was not renabled).

Upvotes: 0

Kirby Todd
Kirby Todd

Reputation: 11556

setUserInteractionEnabled = NO on the view you want to disable

Upvotes: -1

madewulf
madewulf

Reputation: 1910

Beware of the code given as solution here by Krishnabhadra:

[[yourSuperView subviews]makeObjectsPerformSelector:@selector(setUserInteractionEnabled:) withObject:[NSNumber numberWithBool:FALSE]];

This will not work in all cases because [yourSuperView subviews] only gives the direct subviews of the superview. To make it work, you will have to iterate recursively on all subviews:

-(void) disableRecursivelyAllSubviews:(UIView *) theView
{
    theView.userInteractionEnabled = NO;
    for(UIView* subview in [theView subviews])
    {
        [self disableRecursivelyAllSubviews:subview];
    }
}

-(void) disableAllSubviewsOf:(UIView *) theView
{
    for(UIView* subview in [theView subviews])
    {
        [self disableRecursivelyAllSubviews:subview];
    }
} 

Now a call to disableAllSubviewsOf will do what you wanted to do.

If you have a deep stack of views, the solution by lxt is probably better.

Upvotes: 8

lxt
lxt

Reputation: 31304

There are a couple of ways of doing this. You could iterate through all your other subviews and set userInteractionEnabled = NO, but this is less than ideal if you have lots of other views (you would, after all, have to subsequently renable them all).

The way I do this is to create an invisible UIView that's the size of the entire screen that 'blocks' all the touches from going to the other views. Sometimes this is literally invisible, other times I may set it to black with an alpha value of 0.3 or so.

When you expand your main subview to fill the screen you can add this 'blocking' UIView behind it (using insertSubview: belowSubview:). When you minimize your expanded subview you can remove the invisible UIView from your hierarchy.

So not quite built-in, but I think the simplest approach. Not sure if that was what you were thinking of already, hopefully it was of some help.

Upvotes: 47

Related Questions