ios - 遍历数组并更改每个 UITableView Cell 的背景颜色

标签 ios swift uitableview uicolor

我正在尝试更好地理解 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/

相关文章:

ios - Swift 中两位小数之间的随机数

iphone - 解读苹果的交易收据

xcode - 为什么 autoshrink 不能正常工作?

ios - 如何在 Swift 中的 View 之间传递数据

ios - swift 3 : UITableViewCell disable selection style also disables selection

iOS - 是否可以在将图像文件从应用程序保存到 iPhone 设备库之前重命名图像文件名?

ios - 使用json从本地文件传递数据

swift 。无法构建 objective-c 模块 'Alamofire'

iphone - 在 iPhone 上选择 tableView 单元格

ios - 在 swift 中关闭 tableView 后再次查看复选标记