首页 > 解决方案 > 设置标签文本结构数组字符串

问题描述

我有 TableView 并想设置位于我的结构数组中的所有 TableViewCell 标签(其中 5 个)特定字符串

我尝试了 for in loop inTableViewCell但似乎不起作用

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  let cell:TableViewCell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewCell
  cell.configure(with: cars[indexPath.section])    //
  return cell
    }
///TableViewCell
    func configure(with cars:Cars){
        for car in cars.carModel{
            lbl.text = cars.carModel[car]     //code crashes here 
        }
///Array
struct Cars {
    let carName:String
    let carModel:[String]
    subscript(index: Int) -> String {
        return carModel[index]
    }
}

let cars:[Cars] = [
    Cars(carName: "Mercedes", carModel: ["S Class","A Class", "B Class"]),
    Cars(carName: "BMW", carModel: ["X5","X6","X7"]),
    Cars(carName: "Ford", carModel: ["Fuison","Focus","Mustang"]),
    Cars(carName: "Toyota", carModel: ["Camry", "Corolla"]),
    Cars(carName: "Hyundai", carModel: ["Elantra"])
]

标签: iosswiftuitableviewuikit

解决方案


您需要使用 enumerated() 函数。当您实际上应该为整数下标时,您尝试为字符串下标。

func configure(with cars: Cars) {
    for (index, car) in cars.carModel.enumerated() {
        lbl.text = cars.carModel[index] 
}

但实际上在这种情况下您甚至不需要这样做。你也可以这样做:

func configure(with cars: Cars) {
    for car in cars.carModel {
        lbl.text = car
}

cars.carModel是一个String类型的列表,表示car是一个字符串。您可以直接使用它。


推荐阅读