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)
我哪里错了?
使用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)
| 归档时间: |
|
| 查看次数: |
385 次 |
| 最近记录: |