ios - 将数据提供给具有多个标签的自定义 UITableViewCell 的最佳方法是什么 - Swift

标签 ios arrays swift uitableview

我有一个带有自定义 viewCell 的 tableView,它具有三个标签,displayCarNamedisplayMpgdisplayCarPrice。我正在使用三个不同的数组来为 tableView 中的每个标签提供数据,一切正常,但我觉得有更好的方法可以做到这一点,可能是使用单个字典或类似的东西。

这是我正在使用的代码。

    private var carNameList = [String]()
    private var mpgList = [Int]()
    private var carPriceList = [Double]()


    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return carNameList.count
    }

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("reusableCell", forIndexPath: indexPath) as! CustomCell

        cell.displayCarName!.text= carNameList[indexPath.row]
        cell.displayMpg!.text = String(mpgList[indexPath.row])
        cell.displayCarPrice!.text = String(carPriceList[indexPath.row])

        return cell
    }

这是在表格行中提供多个标签的常用方法吗?如果没有,有人可以帮我改进上面显示的代码吗?

仅供引用 - 我实际上每行有三个以上的标签,但为简单起见,我只显示三个。

谢谢

最佳答案

您使用的有时称为平行阵列。这种方法在缺乏结构支持的语言中很常见。

由于 Swift 确实支持结构,更好的方法是定义一个表示 Car 的类,其中三个属性分别为汽车的 NameMpgPrice,然后使用 [Car] 的单个列表代替三个单独的列表:

class Car {
    let Name : String
    let Mpg : Int
    let Price : Double
    init(name: String, mpg : Int, price : Double ) {
        Name = name
        Mpg = mpg
        Price = price
    }
}
...
private var carList = [Car]()
...
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("reusableCell", forIndexPath: indexPath) as! CustomCell
    Car car = carList[indexPath.row]
    cell.displayCarName!.text= car.Name
    cell.displayMpg!.text = String(car.Mpg)
    cell.displayCarPrice!.text = String(car.Price)
    return cell
}

关于ios - 将数据提供给具有多个标签的自定义 UITableViewCell 的最佳方法是什么 - Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34999673/

相关文章:

ios - Swift:为什么从 NSManagedObject 继承会破坏我的属性?

iphone - 如何将本 map 片保存到在线数据库

c - 使用动态数组的段错误

ios - viewdidload 操作顺序中的网页内容数组很奇怪

swift - 将 String 类型转换为 Error 是不可预测的

ios - Realm 洗牌 RLMArray

ios - 预期申报错误

r - 如何同时对数组中的所有矩阵进行计算

数组或部分中的 Javascript 字符串

ios - 如何在表格 View 中的单元格之间放置临时单元格?