ios - 设置标签文本结构数组字符串
问题描述
我有 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"])
]
解决方案
您需要使用 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
是一个字符串。您可以直接使用它。
推荐阅读
- php - 在给定的秒数内刷新 ajax 代码
- javascript - 如何使用 Vue Cli 3 配置 Webpack-simple?
- search - 与 DNN 搜索集成(将搜索功能添加到自己的搜索输入、搜索结果和索引自定义模块)
- swift - 在绘图应用程序中快速合并图像视图
- python-2.7 - 将 Selenium 与 Gitlab CI 集成
- java - 无法在 Java 中解析 web.xml 文件
- android - 在 ~/android-build\build\outputs\apk\debug 中生成的 Qt Android 输出 apk
- python-3.x - 将包含整数和字符串的列表转换为嵌套元组,Python
- c++ - 即时将 C++ 仿真数据写入 HDF5 文件
- sql - 减号或破折号 SQL ms Access 的验证规则