在swift中覆盖UIView中的默认图层类型 [英] Overriding default layer type in UIView in swift

查看:242
本文介绍了在swift中覆盖UIView中的默认图层类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在swift中继承UIView,并且使用CAShapeLayer是此子类的图层类型 - 使用layerClass()覆盖图层类型。

I want to subclass UIView in swift, and use a CAShapeLayer is the layer type for this subclass - overriding the layer type with layerClass().

如何访问CAShapeLayer中的属性,但不访问CALayer中的属性 - 例如下面示例中的路径。下面的代码无法编译,因为path不是CALayer的成员。

How do I access properties that are in CAShapeLayer, but not in CALayer - such as path in the example below. The code below does not compile because path is not a member of CALayer.

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

override func awakeFromNib() {

    var path: UIBezierPath = UIBezierPath.init(ovalInRect: CGRectMake(0, 0, 30, 10))

    self.layer.path = path.CGPath
}


推荐答案

请注意,self.layer总是在UIView中返回一个通用的CALayer,所以你必须将它强制转换为你的特定类,以确保它具有正确的类型。您可以执行以下操作以确保调用CAShapeLayer的路径而不是CALayer类类型。

Note that self.layer always returns a generic CALayer inside a UIView, so you have to typecast it to your specific class to make sure that it has the correct type. You can do the following to make sure that you call path to CAShapeLayer not to CALayer class type.

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

    override func awakeFromNib() {
        guard let shapeLayer = self.layer as? CAShapeLayer else { return }

         let path: UIBezierPath = UIBezierPath.init(ovalInRect: CGRectMake(0, 0, 30, 10))
        shapeLayer.path = path.CGPath
    }

这篇关于在swift中覆盖UIView中的默认图层类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆