设置标签文本结构数组字符串



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

我尝试在TableViewCell中进行循环,但似乎不起作用

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

您需要使用enumated()函数。您试图对字符串下标,而实际上应该对整数下标。

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是字符串。你可以直接使用

相关内容

  • 没有找到相关文章

最新更新