Reputation: 639
I am trying to better understand UITableViews and building them from scratch. I want to build a table view that displays a different background color for each cell. I have built out a ColorModel class that holds an array of type UIColors. All of my tableview cells are displaying a red background which is the last color in the array. Here is that snippet:
import Foundation
import UIKit
class ColorModel {
static var colors = [
UIColor.white,
UIColor.blue,
UIColor.black,
UIColor.brown,
UIColor.cyan,
UIColor.green,
UIColor.red
]
}
Here is my main view controller syntax:
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
var colorList = ColorModel.colors
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
tableView.delegate = self
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return colorList.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ColorCell", for: indexPath)
for color in colorList {
cell.backgroundColor = color
}
return cell
}
}
Where am I going wrong?
Upvotes: 0
Views: 1064
Reputation: 100503
Use indexPath.row
to get the color for every cell from the array
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ColorCell", for: indexPath)
let color = colorList[indexPath.row]
cell.backgroundColor = color
return cell
}
Upvotes: 5