How to add methods to NSTableViewDelegate protocol?

562 views Asked by At

I'd like to expand NSTableViewDelegate protocol with a few custom methods. For instance, I want my custom NSTableView subclass to inform the delegate on some specific events. Is it possible not to create another protocol but to add custom methods to the existing one? What would be the best approach here?

I've tried to write and extension to NSTableViewDelegate, and methods get called, but in this extension I have no access to the delegate class (my subclass of NSViewController). And it kind of ruins the whole idea, because the controller needs to respond to events in its specific way.

So: how one could add methods to NSTableViewDelegate protocol and provide implementation in the delegate class?

Sorry for verbosity :)

Example code (in the project it differs a bit, but the idea is the same):

extension NSTableViewDelegate {
    func didBecomeFirstResponder(_ tableView: NSTableView) {
        isTableViewFirstResponder = true //warning: Use of unresolved identifier 'isTableViewFirstResponder'
    }

    func didResignFirstResponder(_ tableView: NSTableView) {
        isTableViewFirstResponder = false   //warning: Use of unresolved identifier 'isTableViewFirstResponder'
    }
}

isTableViewFirstResponder is a property of the delegate class. Swift just doesn't know where to look for it. How can I specify the class where isTableViewFirstResponder is declared?

2

There are 2 answers

0
Zverusha On BEST ANSWER

It is possible to add a method to this protocol. But the implementation will reside in extension, there is no obvious way to implement additional methods in the class that conforms the protocol.

7
shallowThought On

You are extending the NSTableViewDelegate protocol and thus can see only stuff that exists in NSTableViewDelegates implementation. isTableViewFirstResponder does not exist in NSTableViewDelegates implementation and thus is not known to the extension.

Afaik it is not possible to add a stored property to an extension, thus I think you have to introduce an extra Protcol, which also makes sense imo. as it is no delegate responsability, but a responder one:

protocol NSTableViewResponder {
    var isTableViewFirstResponder: Bool {get set}
}

extension NSTableViewResponder {
    mutating func didBecomeFirstResponder(_ tableView: NSTableView) {
        isTableViewFirstResponder = true
    }

    mutating func didResignFirstResponder(_ tableView: NSTableView) {
        isTableViewFirstResponder = false
    }
}