Viper OS X
Viper OS X

Reputation: 283

How to disable user interaction in a custom View

I have a custom View NSView and I want to disable userinteraction, but I'm not sure how to do this.

My idea was:

[myView setEnabled:NO];

but it's wrong and doesn't work. How can I make it so that, it's just visible for the user, and nothing else?

Upvotes: 18

Views: 13308

Answers (6)

Soid
Soid

Reputation: 2881

The solutions here didn't work for me: as someone mentioned, the keyboard interaction are not disabled, and the like issues. Additionally, my custom view changed the mouse cursor to the hand icon, showing intractability, even if interaction was disabled via one of the approaches.

I ended up removing the view and adding it back later. Since I just drew an opaque layer on top of my custom view, I didn't need to display anything. So removing it (and adding it back when needed) worked better.

Upvotes: -1

Honghao Z
Honghao Z

Reputation: 1537

I think overriding hitTest(_:) is not ideal as it can block all interactions behind it.

A better way is to make the view refuse to becomeFirstResponder. So that events can be send to next responder, basically it skips the view.

class SubclassNSView: NSView {

  public var isUserInteractionEnabled: Bool = true

  open override func becomeFirstResponder() -> Bool {
    if isUserInteractionEnabled == false {
      return false
    } else {
      return super.becomeFirstResponder()
    }
  }
}

Upvotes: 0

Joey
Joey

Reputation: 2978

Here is an example in Swift 4. Place your views into this custom view.

class UserInterectionDisabledView: NSView {
    override func hitTest(_ point: NSPoint) -> NSView? {
        return nil
    }
}

Upvotes: 3

Muruganandham K
Muruganandham K

Reputation: 5331

subclass the NSView and add following method

-(void)mouseDown:(NSEvent *)theEvent
{

}

Upvotes: 3

Ravindhiran
Ravindhiran

Reputation: 5384

NSView doesn't have either setEnabled: or setIgnoresMouseEvents:

Implement the hitTest: method to return nil.

Upvotes: 17

trojanfoe
trojanfoe

Reputation: 122458

From here:

//
//  NSView-DisableSubsAdditions.m
//  Can Combine Icons
//
//  Created by David Remahl on Tue Dec 25 2001.
//  Copyright (c) 2001 Infinity-to-the-Power-of-Infinity. All rights reserved.
//

#import "NSView-DisableSubsAdditions.h"

@implementation NSView(DisableSubsAdditions)

- (void)disableSubViews
{
    [self setSubViewsEnabled:NO];
}

- (void)enableSubViews
{
    [self setSubViewsEnabled:YES];
}

- (void)setSubViewsEnabled:(BOOL)enabled
{
    NSView* currentView = NULL;
    NSEnumerator* viewEnumerator = [[self subviews] objectEnumerator];

    while( currentView = [viewEnumerator nextObject] )
    {
        if( [currentView respondsToSelector:@selector(setEnabled:)] )
        {
            [(NSControl*)currentView setEnabled:enabled];
        }
        [currentView setSubViewsEnabled:enabled];

        [currentView display];
    }
}

@end

Upvotes: 3

Related Questions