我有一个与设计相关的问题。
有一个继承自 CAShapeLayer 的类和另一个继承自 CATextLayer 的类,它们都符合某种协议(protocol),如下所示。
protocol HogeProtocol {
func aFunction()
}
class A: CAShapeLayer, HogeProtocol {
func aFunction() {
print("I am Class A")
}
}
class B: CATextLayer, HogeProtocol {
func aFunction() {
print("I am Class B")
}
}
UIView 的子类有一个确认此协议(protocol)的对象数组:
class CustomView: UIView {
var customLayers = [HogeProtocol]()
func callTheFunctionAndAddSublayer() {
// some implementation
}
}
我在这里尝试做的是调用 customLayers 的 aFunction() 并将它们添加到此自定义 UIView 的图层中。
class CustomView: UIView {
var customLayers = [HogeProtocol]()
func callTheFunctionAndAddSublayer() {
for customLayer in customLayers {
customLayer.aFunction() // can call
layer.addSublayer(customLayer) // cannot call..
}
}
}
在这种情况下,元素正在确认协议(protocol),但不能添加到子层,因为它们不是从 CALayer 继承的。我希望我可以创建一个从 CALayer 继承的对象数组(这是 CAShapeLayer 和 CATextLayer 的公共(public)父类)并确认协议(protocol),但 swift 不允许我这样做(据我所知......)
这似乎是一个非常简单的问题,我猜可能已经有了解决方案,但经过几个小时的谷歌研究后我找不到任何答案...... 有什么想法吗?
最佳答案
您需要使用 as?
或 as!
将数组对象向下转换为 CALayer。
关于ios - 如何制作一个确认某个协议(protocol)并具有不同父类的对象数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32556377/