我有一个带有自定义 viewCell 的 tableView,它具有三个标签,displayCarName
、displayMpg
和 displayCarPrice
。我正在使用三个不同的数组来为 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
的类,其中三个属性分别为汽车的 Name
、Mpg
和 Price
,然后使用 [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/