我正在尝试更好地理解Uitable Views并从头开始构建它们。我想构建一个表视图,为每个单元格显示不同的背景颜色。我已经建立了一个拥有一系列类型Uicolors的colormodel类。我所有的桌面电视单元格都显示了红色背景,这是数组中的最后颜色。这是那个片段:
import Foundation
import UIKit
class ColorModel {
static var colors = [
UIColor.white,
UIColor.blue,
UIColor.black,
UIColor.brown,
UIColor.cyan,
UIColor.green,
UIColor.red
]
}
这是我的主视图控制器语法:
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
}