swiftoverridingclass-extensions

Trying to override NSView's drawRect from extension class


I am designing an NSView class extension in Swift. Inside that extension class, I am trying to override drawRect using this

extension NSView {


  override func drawRect(rect: NSRect) {


  }

There is an error pointing to the override and saying Method does not override any method from its superclass... Method drawRect with Objective-C (???) selector 'drawRect' conflicts with the previous declaration with the same Objective-C selector

What? Objective-C? I am using swift.

What is going on?


Solution

  • You are extending not subclassing and then overriding a method which was already defined by the superclass.

    drawRect is already defined by NSView, that's why the conflict with already defined ...

    In order to do a custom view you are intended to define your own subclass of NSView and override your subclass's drawRect implementation.

    class MyView: NSView {
    
        override func drawRect(rect: NSRect) {
    
         // Your custom implementation ....
    
        } 
    }
    

    Hope this helps