【问题标题】:Swift Alternating UITableViewCell gradient colorSwift交替UITableViewCell渐变颜色
【发布时间】:2018-10-23 02:17:29
【问题描述】:

我曾经在 tableView willDisplay cell 方法中使用此代码,但它并没有准确地交替颜色 - 它几乎做到了,但有时仍然会混淆 1 或 2 个相同的颜色,我不确定。

我发现一些建议在我的自定义 UITableViewCell 类中调用 awakeFromNib 方法中的所有方法,所以我像这样移动了所有内容:

class SectionTableViewCell: UITableViewCell {
    @IBOutlet weak var lblName: UILabel!
    @IBOutlet weak var lblValue: UILabel!

    var cellGradient_1: CAGradientLayer = CAGradientLayer()
    var cellGradient_2: CAGradientLayer = CAGradientLayer()

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
        self.layer.insertSublayer(cellGradient_1, at: 0)
        self.layer.insertSublayer(cellGradient_2, at: 0)
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        cellGradient_1.frame = self.bounds
        cellGradient_2.frame = self.bounds
    }

}

现在,在我的tableView cellForRowAt 中进行检查:

let cell = tableView.dequeueReusableCell(withIdentifier: "Section", for: indexPath) as! SectionTableViewCell
if (indexPath.row%2 == 0) {
    cell.cellGradient_1.colors = theme.childColor_1 //Some gradient color
}
else{
    cell.cellGradient_2.colors = theme.childColor_2 //Some gradient color
}

它们现在都是第一种颜色,靠近底部的 1 是第二种颜色。我对nib 做错了吗?有没有不同的方法来设置渐变的颜色?任何帮助将不胜感激。

编辑:看起来它适用于初始加载,但是一旦重新加载表格或发生滚动,所有单元格的渐变都会更改为初始值,除了 2 或 3。

【问题讨论】:

    标签: ios swift uitableview cagradientlayer


    【解决方案1】:

    您使用两层,第一层覆盖第二层。
    要解决这个问题,只需删除第二层并将tableView cellForRowAt 中的代码更改为:

    let cell = tableView.dequeueReusableCell(withIdentifier: "Section", for: indexPath) as! SectionTableViewCell
    if (indexPath.row%2 == 0) {
        cell.cellGradient_1.colors = theme.childColor_1 //Some gradient color
    }
    else{
        cell.cellGradient_1.colors = theme.childColor_2 //Some gradient color
    }
    

    (我将 cell.cellGradient_2 替换为 cell.cellGradient_1)

    【讨论】:

    • 啊啊啊啊,现在我觉得有点傻。非常感谢您的关注!完美运行。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-12
    相关资源
    最近更新 更多