How do you override layerClass in swift

后端 未结 4 1774
醉话见心
醉话见心 2021-02-04 23:45

In Objective-C we use to do it like this

+ (Class)layerClass
{
    return [CAEAGLLayer class];
}

Obviously this won\'t work:

CA         


        
相关标签:
4条回答
  • 2021-02-05 00:13

    Swift does introspection much differently than Objective-C. You may want to take a look at the docs about Metatypes.

    For your case I'd try: CAEAGLLayer.self

    0 讨论(0)
  • 2021-02-05 00:28

    In iOS 10, this is a calculated property instead of a method:

    override class var layerClass: AnyClass {
        get {
            return CAEAGLLayer.self
        }
    }
    
    0 讨论(0)
  • 2021-02-05 00:31

    Adapted from Apple's ListerKit sample code:

    override class func layerClass() -> AnyClass {
        return CAEAGLLayer.self
    }
    

    Update for Swift 3:

    override class var layerClass: AnyClass {
        get {
            return CAGradientLayer.self
        }
    }
    
    0 讨论(0)
  • 2021-02-05 00:33

    It can be written like this

    import UIKit
    
    class GradientView: UIView {
    
        override final class var layerClass: AnyClass {
            return CAGradientLayer.self
        }
    }
    

    Bonus tip: Maybe you would like to have a type safe getter to the layer? Then you can write

    import UIKit
    
    class GradientView: UIView {
    
        override final class var layerClass: AnyClass {
            return CAGradientLayer.self
        }
    
        override var layer: CAGradientLayer {
            return super.layer as! CAGradientLayer
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题