2016-12-18 166 views
0

如何动态更改表格视图单元格的颜色。 我想要获得类似于截图中所示的内容,请提出建议。如何动态更改表格视图单元格的颜色

enter image description here

在此先感谢。

+0

迅速或objectiv- C? –

+0

你得到的两个答案都给了你根据单元格的indexPath分配颜色的方法。你需要做的是找出你想要的细胞颜色,以及如何生成这些颜色。你想要你在示例图像中显示的特定颜色? 我建议把你的样本颜色加入到Photoshop这样的照片编辑器中,对每一个的RGB值进行采样,并且提出一个颜色值数组(如@ tejendrasingh的答案)或者生成这些颜色值的函数每一步(如Adrian的回答)。 –

+0

你会有多少个细胞?您需要分散从开始到结束单元格的颜色变化。 –

回答

0

这是很容易做到:

我在下面给出一个演示:

enter image description here

  1. 首先,将一个tableViewvc

enter image description here

  • 其次,设置tableView的代表且dataSource:
  • enter image description here

  • 第三步,在你的vc中,设置data

    import UIKi牛逼

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

    @IBOutlet弱VAR的tableView:UITableView的!

    var cellCount:Int! = 6

    VAR cus_color:的UIColor = UIColor.init(红色:35/255.0,绿:204/255.0,蓝色:216.0/255.0,α-: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) 
    } 
    
    } 
    
  • 0

    您可以使用UITableViewCell属性backgroundColor来动态设置单元格颜色。

    例 -

    -(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; 
    } 
    
    相关问题