ios - 无法添加 CAGradientLayer 以显示在 UIView 子类中

标签 ios iphone swift ios8 quartz-core

我有这个 UIView 子类,我想用它来显示自定义 View 。问题是我无法让自定义 CAGradientLayer 显示在我的 View 中……我仍然将其视为红色条纹。

public class PSTLoadingBar : UIView {

private var loadingBarView: UIView!
private var gradientLayer: CAGradientLayer!

required public init(coder aDecoder: NSCoder) {
    fatalError("Not coder compliant")
}

public override var frame: CGRect {
    didSet {

        if frame == CGRect.zeroRect {
            return
        }

        loadingBarView.frame = frame
    }
}

// MARK: - Singleton
public class var sharedInstance: PSTLoadingBar {
    struct Singleton {
        static let instance = PSTLoadingBar(frame: CGRect.zeroRect)
    }
    return Singleton.instance
}

public override init(frame:CGRect) {

    super.init(frame:frame)

    loadingBarView = UIView()
    loadingBarView.backgroundColor = UIColor.redColor()

    gradientLayer = CAGradientLayer()
    gradientLayer.frame = loadingBarView.bounds
    gradientLayer.opacity = 1

    let color1 = UIColor(red: 67/255, green: 36/255, blue: 84/255, alpha: 1).CGColor
    let color2 = UIColor(red: 67/255, green: 36/255, blue: 84/255, alpha: 1).CGColor

    let colors = [color1, color2]

    gradientLayer.startPoint = CGPointMake(0,0.5)
    gradientLayer.endPoint = CGPointMake(1.0, 0.5)
    gradientLayer.colors = colors


    loadingBarView.layer.insertSublayer(gradientLayer, atIndex:0)

    addSubview(loadingBarView)

}

// MARK: - Public Methods
public class func show(parentView: UIView) {

    let loadingBar = PSTLoadingBar.sharedInstance

    let _view = UIApplication.sharedApplication().keyWindow?.rootViewController?.view

    if let _view = _view {

        loadingBar.frame = CGRectMake(0, 32, _view.bounds.width, 5)


        if loadingBar.superview == nil {
            _view.addSubview(loadingBar)
        }

    }
}

我试过在各种索引中添加子层,我也尝试过使用 self.layer 而不是 loadingBar.layer 但还是没有成功。

我怀疑我需要从 UIView 重写另一个方法,但我不确定是否是这种情况。

有什么想法吗?

最佳答案

当您创建 loadingBarView 时,它的框架是 CGRectZero——一个宽度和高度为零的矩形——这导致渐变层同样具有零宽度和高度,因此不会出现。在 -layoutSubviews 中添加图层不是必需的——您只需将其框架更新为 loadingBarView 的边界即可。

关于ios - 无法添加 CAGradientLayer 以显示在 UIView 子类中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28907605/

相关文章:

iOS后台获取

shell - swift 错误 : launch path not accessible

html - NSAttributedString 到 iOS Swift 3 中的 HTML

ios - 如何在 UIView 上使用 UIPanGestureRecognizer 时禁用滚动

ios - 如果要使用主 Storyboard文件,应用程序委托(delegate)必须实现 window 属性

ios - UIPercentDrivenInteractiveTransition 取消问题

iphone - 使用 POST 参数通过 UIWebView 加载网页

ios - 如何在 iOS 中手动触发 touchesBegan 值?

iphone - 自定义 UITextField/UIButton

swift - 为什么在具有 Comparable 约束的泛型函数中会丢失泛型类型信息?