Reputation: 227
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.
Upvotes: 0
Views: 1912
Reputation: 26896
It is easy to do:
I give a demo below:
tableView
to vc
:tableView
's delegate and dataSource:The third step, in your vc
, set the data
:
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
var cellCount:Int! = 6
var cus_color:UIColor = UIColor.init(red: 35 / 255.0, green: 204/255.0, blue: 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)
}
}
Upvotes: 1
Reputation: 1
You can use UITableViewCell property backgroundColor to set cell color dynamically.
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;
}
Upvotes: 0