How to conform NSView to CALayerDelegate when you import SwiftUI?

This compiles:

import AppKit

class CustomView: NSView, CALayerDelegate {}

This does not however:

import AppKit
import SwiftUI

class CustomView: NSView, CALayerDelegate {}

This is an error:

... error: redundant conformance of 'CustomView' to protocol 'CALayerDelegate'
class CustomView: NSView, CALayerDelegate {}
                          ^
... note: 'CustomView' inherits conformance to protocol 'CALayerDelegate' from superclass here
class CustomView: NSView, CALayerDelegate {}
      ^

Any idea how to fix this?

If you remove CALayerDelegate conformance, delegate methods are not called.

They're not called because the compiler can't see they're implementing the protocol and thus won't make them available from Objective-C. But you can still make it available manually with the @objc attribute. You should also specify the Objective-C selector name (which isn't always the same name as in Swift), like so:

@objc(displayLayer:)
func display(_ layer: CALayer) { /* your implementation here */ }
1 Like

It works, thank you so much Michel! Could you please reply here as well? https://stackoverflow.com/questions/58461756/how-to-conform-nsview-to-calayerdelegate-when-you-import-swiftui

Terms of Service

Privacy Policy

Cookie Policy