导入SwiftUI时如何使NSView与CALayerDelegate兼容?

问题描述 投票:2回答:1

此编译:

import AppKit

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

但是,这不是:

import AppKit
import SwiftUI

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

这是一个错误:

... 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 {}
      ^

任何想法如何解决此问题?

如果删除CALayerDelegate一致性,则不会调用委托方法。

calayer swiftui nsview appkit calayerdelegate
1个回答
4
投票

之所以没有被调用,是因为编译器看不到他们正在实现协议,因此无法在Objective-C中使用它们。但是您仍然可以使用@objc属性使其手动可用。您还应该指定Objective-C选择器名称,该名称不一定与Swift中的名称相同:

import AppKit
import SwiftUI

class CustomView: NSView {
    @objc(layoutSublayersOfLayer:)
    func layoutSublayers(of layer: CALayer) {}
}
© www.soinside.com 2019 - 2024. All rights reserved.