【问题标题】:Gradually change TableViewCell layer background color depending on scroll percentage根据滚动百分比逐渐改变 TableViewCell 图层背景颜色
【发布时间】:2020-04-23 15:08:40
【问题描述】:

我需要一些帮助,在滚动时根据渐变颜色数组逐渐更改 TableViewCell 的图层背景颜色

let gradientColors = [UIColor.red, UIColor.blue, UIColor.green, UIColor.cyan]

因此,从屏幕顶部到中间的可见单元格的背景颜色在UIColor.red -> UIColor.blue 之间,从屏幕中间到底部的背景颜色在UIColor.green -> UIColor.cyan 之间。 注意它们应该在滚动时逐渐改变背景颜色。

【问题讨论】:

    标签: ios arrays swift uitableview


    【解决方案1】:

    如果在 UIViewController 的视图之上添加 tableView:

    import UIKit
    
    class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    
    @IBOutlet weak var tblView: UITableView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
    
        tblView.delegate = self
        tblView.dataSource = self
    
        //Make background of tableView transparent
        tblView.backgroundColor = .clear
    
        // Create gradient background
        let gradient = CAGradientLayer()
        gradient.frame = view.bounds
        gradient.colors = [UIColor.red.cgColor, UIColor.blue.cgColor, UIColor.green.cgColor, UIColor.cyan.cgColor]
        view.layer.insertSublayer(gradient, at: 0)
    }
    
    
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 10 //as an example
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
        cell.backgroundColor = .clear // make cell to have Clear colour
        return cell
    }
    }
    

    如果您想要一些不透明度以使单元格更可见,您可以将“.clear”更改为“UIColor.white.withAlphaComponent(0.2)”,这样顶部的文本将更具可读性

    【讨论】:

    • 谢谢,但我想逐渐改变单元格的背景而不是表格视图
    • 因为视图位于 tableView 后面(确保您的控制器是 UIViewController 而不是 UITableViewController)并且单元格是透明的,当您滚动时,单元格渐变会根据后面的内容而变化,因此看起来像单元格正在改变渐变颜色。如果我理解错了,你能发一张它应该是什么样子的图片吗?你的意思是一个单元格应该是一种纯色(无渐变)?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-09
    相关资源
    最近更新 更多