简体   繁体   中英

Iterate through array and change background color of each UITableView Cell

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?

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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