Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to conform NSView to CALayerDelegate when you import SwiftUI?

This compiles:

import AppKit

class CustomView: NSView, CALayerDelegate {
    func layoutSublayers(of layer: CALayer) {}
}

This does not however:

import AppKit
import SwiftUI

class CustomView: NSView, CALayerDelegate {
    func layoutSublayers(of layer: CALayer) {}
}

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.

like image 234
Vadim Avatar asked Mar 03 '23 07:03

Vadim


1 Answers

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:

import AppKit
import SwiftUI

class CustomView: NSView {
    @objc(layoutSublayersOfLayer:)
    func layoutSublayers(of layer: CALayer) {}
}
like image 177
Michel Fortin Avatar answered May 07 '23 15:05

Michel Fortin