简体   繁体   English

如何动态更改表格视图单元格的颜色

[英]How to change the color of a table view cell dynamically

How to change the colour of the table view cell dynamically . 如何动态更改表格视图单元格的颜色。 I want to achieve something like shown in screenshot please suggest. 我想实现类似屏幕快照所示的功能,请提出建议。

在此处输入图片说明

Thanks in advance. 提前致谢。

You can use UITableViewCell property backgroundColor to set cell color dynamically. 您可以使用UITableViewCell属性backgroundColor来动态设置单元格颜色。

Example- 例-

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    UITableViewCell* cell = [self.tableView dequeueReusableCellWithIdentifier:@"Cell"];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"];
    }
    //cellColorHolder is UIColor object type array.
    cell.backgroundColor = (UIColor*)[cellColorHolder objectAtIndex:indexPath.row];
    return cell;
}

It is easy to do: 很容易做到:

I give a demo below: 我在下面给出一个演示:

在此处输入图片说明

  1. Firstly, drag a tableView to vc : 首先,将tableView拖到vc

在此处输入图片说明

  1. Secondly, set the tableView 's delegate and dataSource: 其次,设置tableView的委托和dataSource:

在此处输入图片说明

  1. The third step, in your vc , set the data : 第三步,在您的vc ,设置data

    import UIKit 导入UIKit

    class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { ViewController类:UIViewController,UITableViewDelegate,UITableViewDataSource {

    @IBOutlet weak var tableView: UITableView! @IBOutlet弱var tableView:UITableView!

    var cellCount:Int! var cellCount:Int! = 6 = 6

    var cus_color:UIColor = UIColor.init(red: 35 / 255.0, green: 204/255.0, blue: 216.0/255.0, alpha: 1.0) var cus_color:UIColor = UIColor.init(红色:35 / 255.0,绿色:204 / 255.0,蓝色:216.0 / 255.0,alpha:1.0)

     override func viewDidLoad() { super.viewDidLoad() self.tableView.separatorStyle = .none } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 100 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return cellCount } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = UITableViewCell() // or your custom cell let perLevel:CGFloat = CGFloat(1.0) / CGFloat(self.cellCount) cell.backgroundColor = UIColor.init(red: 35 / 255.0, green: 204/255.0, blue: 216.0/255.0, alpha: (perLevel + CGFloat(indexPath.row) * perLevel)) return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { self.tableView.deselectRow(at: indexPath, animated: false) } } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM