根据滚动百分比逐渐更改TableViewCell图层的背景颜色

时间:2020-04-23 15:08:40

标签: ios arrays swift uitableview

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

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

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

1 个答案:

答案 0 :(得分:0)

如果在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)”,这样顶部的文本将更具可读性

相关问题