代码之家  ›  专栏  ›  技术社区  ›  Johan van den Berg

Swift UITableView中的渐变层

  •  0
  • Johan van den Berg  · 技术社区  · 7 年前

    我想在Swift中UITableView的每一行中创建一个渐变背景层。在cellForRowAt函数中,我有一段代码来绘制渐变层。

    guard let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as? PlayerTableViewCell else { fatalError("The dequeued cell is not an instance of PlayerTableViewCell") }
    
    // set background color for the cell
    let newLayer = CAGradientLayer()
    newLayer.colors = [UIColor.black.cgColor, UIColor.darkGray.cgColor ]
    newLayer.frame = cell.frame
    cell.layer.addSublayer(newLayer)
    cell.layer.insertSublayer(newLayer, at: 0)
    

    当我运行此代码时,只有表中的第一个条目具有渐变层,其他单元格具有默认背景。 我需要添加什么吗?

    Missing background gradient color in table cells

    2 回复  |  直到 7 年前
        1
  •  3
  •   Milan Nosáľ    7 年前

    问题是 gradientLayer 当superview的帧更改时,不会更新其边界-因此当superview更改其帧时 渐变层 仍将保持相同的边界。您需要在中更新其边界 layoutSubviews

    我同意@Jay的回答,但有一些问题:

    var gradientLayer: CAGradientLayer = CAGradientLayer()
    
    
    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
    
        // insert it only once
        gradientLayer.colors = [UIColor.black.cgColor, UIColor.darkGray.cgColor ]
        contentView.layer.insertSublayer(gradientLayer, at: 0)
    
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        // here we just need to update the frame
        gradientLayer.frame = contentView.frame
    }
    

    我已经测试过了,效果很好(好吧,@Jay的答案似乎对这件事也很有效)。

        2
  •  3
  •   Jay    7 年前

    为什么不将其添加到单元格的子类中?这样,您也可以在prepareforeuse中删除它,这样您就不会向单元格中添加倍数了?

    var newLayer:CAGradientLayer!
    
    override func layoutSubviews() {
        super.layoutSubviews()
        //Code to insert the gradient here.
        newLayer = CAGradientLayer()
        newLayer.frame = contentView.frame
        newLayer.colors = [UIColor.black.cgColor, UIColor.darkGray.cgColor ]
        contentView.layer.insertSublayer(newLayer, at: 0)
    }