How to disable user interaction in a custom View

Viewed 11834

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?

5 Answers

NSView doesn't have either setEnabled: or setIgnoresMouseEvents:

Implement the hitTest: method to return nil.

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
    }
}

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()
    }
  }
}
Related