我有这个UIView子类,我想用它来显示自定义视图。问题是我无法在我的视图中显示自定义CAGradientLayer
...我仍然将其视为红色条纹。
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中的另一个方法,但我不确定是否是这种情况。
有什么想法吗?
答案 0 :(得分:4)
创建loadingBarView
时,其框架为CGRectZero - 一个零宽度和高度的矩形 - 这会导致渐变图层的宽度和高度同样为零,因此不会出现。无需在-layoutSubviews
中添加图层 - 您只需将其框架更新为loadingBarView
的边界。