将 subLayer 添加到 UIView 时清除的对象

Objects cleared when adding subLayer to UIView

我正在使用自定义 UIView class,其中包含文本字段和标签,由 Storyboard 提供。当 class 在 class 中添加一个子层时,视图中包含的对象消失,变得透明或者可能变成与 UIView 背景相同的颜色。是否有可以设置的 属性 或可以使用的方法来确保对象保持可见?

提前致谢!

这是我的代码:

class viewBorder: UIView {

    override init(frame: CGRect) {
        super.init(frame: frame)
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    override func drawRect(rect: CGRect) {
        super.drawRect(rect)

        // Create a rect with only 1x rounded corner
        let rectPath = UIBezierPath(roundedRect: bounds, byRoundingCorners: UIRectCorner.TopLeft, cornerRadii: CGSize(width: 21.0, height: 21.0))
        let rectLayer = CAShapeLayer()
        rectLayer.shadowOffset = CGSize(width: -1.5, height: -1.5)
        rectLayer.shadowOpacity = 0.6
        rectLayer.path = rectPath.CGPath
        rectLayer.fillColor = tintColor.CGColor
        self.layer.addSublayer(rectLayer)
    }
}

试试这个:

override func drawRect(rect: CGRect) {
    super.drawRect(rect)

    // Create a rect with only 1x rounded corner
    let rectPath = UIBezierPath(roundedRect: bounds, byRoundingCorners: UIRectCorner.TopLeft, cornerRadii: CGSize(width: 21.0, height: 21.0))
    let rectLayer = CAShapeLayer()
    rectLayer.shadowOffset = CGSize(width: -1.5, height: -1.5)
    rectLayer.shadowOpacity = 0.6
    rectLayer.path = rectPath.CGPath
    rectLayer.fillColor = tintColor.CGColor
    rectLayer.zPosition = -1 // Added
    self.layer.addSublayer(rectLayer)
}