【问题标题】:Set label text struct array string设置标签文本结构数组字符串
【发布时间】:2021-11-27 22:28:26
【问题描述】:

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

我在 TableViewCell 中尝试了 for in 循环,但似乎不起作用

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"])
]

【问题讨论】:

  • 您不能使用字符串索引数组。尝试将多个值分配给单个标签也是没有意义的。你最终会得到最后一个值。可能你想要的是让你的桌子为每辆车都有一个部分,然后是模型中的行。
  • @Paulw11 是的,当然是我的错误,我想要带有字符串的标签行

标签: ios swift uitableview uikit


【解决方案1】:

您需要使用 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 是一个字符串类型的列表,这意味着car 是一个字符串。可以直接使用。

【讨论】:

    猜你喜欢
    • 2012-05-09
    • 2022-11-16
    • 1970-01-01
    • 2021-11-28
    • 2011-10-11
    • 1970-01-01
    • 2017-11-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多