迭代数组并更改每个UITableView Cell的背景颜色

And*_*son 0 uitableview uicolor ios swift

我试图更好地了解UITableViews并从头开始构建它们.我想构建一个表格视图,为每个单元格显示不同的背景颜色.我已经构建了一个ColorModel类,它包含一个UIColors类型的数组.我的所有tableview单元格都显示红色背景,这是数组中的最后一种颜色.这是片段:

import Foundation
import UIKit

class ColorModel {

static var colors = [
    UIColor.white,
    UIColor.blue,
    UIColor.black,
    UIColor.brown,
    UIColor.cyan,
    UIColor.green,
    UIColor.red
]

} 
Run Code Online (Sandbox Code Playgroud)

这是我的主视图控制器语法:

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
}


}
Run Code Online (Sandbox Code Playgroud)

我哪里错了?

Sh_*_*han 5

使用indexPath.row得到的颜色从阵列的每一个细胞

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
}
Run Code Online (Sandbox Code Playgroud)

  • 对于OP:`tableView(cellForRowAt :)函数一次传递一个`indexPath`,并一次返回一个单元格.表视图一遍又一遍地调用它,每次都要求一个不同的单元格.您等待表视图为每个需要显示的单元调用它.你永远不会遍历该方法中的所有单元格. (2认同)