我正在尝试更好地理解 UITableViews 并从头开始构建它们。我想构建一个表格 View ,为每个单元格显示不同的背景颜色。我构建了一个 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
]
}
这是我的主要 View Controller 语法:
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
}
}
我哪里错了?
最佳答案
使用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
}
关于ios - 遍历数组并更改每个 UITableView Cell 的背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48957697/