CALayer只出现一秒钟,然后消失

时间:2017-01-03 19:26:25

标签: ios swift calayer

我将CALayer添加到可滚动对象(UIScrollView,TableView,CollectionView)的顶部和底部,以便在可见区域后面有内容时显示它们。

class TableViewWithCALayers: UITableView {

var topGradientLayer: CAGradientLayer?
var bottomGradientLayer: CAGradientLayer?

override func layoutSubviews() {
    super.layoutSubviews()
    guard self.topGradientLayer != nil && self.bottomGradientLayer != nil else {
        addGradientLayerToTop() // create layer, set frame, etc.
        addGradientLayerToBottom()
        return
    }

//        addGradientLayerToTop()// if uncomment it - multiple layers are created and they are visible, but this is not the solution...
        handleLayerAppearanceAfterLayoutSubviews() // playing with opacity here
    }

我如何创建图层:

func addGradientLayerToTop() {
    if let superview = superview {
        self.topGradientLayer = CAGradientLayer()
        let colorTop =  UIColor.redColor().CGColor
        let colorBottom = UIColor.clearColor().CGColor
        if let topLayer = self.topGradientLayer {
            topLayer.colors = [colorTop, colorBottom]
            topLayer.locations = [0.0, 1.0]
            topLayer.frame = CGRect(origin: self.frame.origin, size: CGSizeMake(self.frame.width, self.layerHeight))
            superview.layer.insertSublayer(topLayer, above: self.layer)
            if (self.contentOffset.y == 0) {
                //                if we are at the top - hide layer
                // topLayer.opacity = 0.0 //temporarily disabled, so it is 1.0
            }
        }
    }
}
除了将TableView与xib文件一起使用外,

TableViewWithCALayers 在各处都运行良好:

class XibFilesViewController : CustomUIViewController, UITableViewDelegate, UITableViewDataSource {

@IBOutlet var tableView: TableViewWithCALayers!

override func viewDidLoad() {
    super.viewDidLoad()
    self.tableView.registerNib(UINib(nibName: "CustomTableViewCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: "CustomTableViewCell")
    self.tableView.layer.masksToBounds = false // this line doesn't help...
}
CustomUIViewController 用于许多其他ViewControllers,其中 TableViewWithCALayers 运行良好,因此不会产生问题。 顶部和底部的图层出现一秒钟,然后消失。来自 LayoutSubviews() func的日志说它们是可见的,不透明度是1.0,但有些内容涵盖了它们。它可以是什么以及如何处理它?<​​/ p>

感谢任何帮助!)

topLayer.zPosition = 10000 //doesn't help
topLayer.masksToBounds = false //doesn't help as well

1 个答案:

答案 0 :(得分:1)

使用nib文件时,这是一个很好的做法,并设计将要绘制图层的UIView添加到原型单元格中,或者标题/页脚,然后让该视图向您的班级确认&#39 ; s实际上处理图层。

相关问题