gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 10:24:50 25 4
gpt4 key购买 nike

我有这个 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com