ios - 如何快速组合数组中的元素并显示在tableView上

标签 ios arrays swift uitableview

我有一个这样的数组:-

var priceArray = [0, 200, 400, 600, 800, 1000]

我从应用程序中的 API 获取了这些数据。我正在使用 tableView 来显示数据所以我可以提供这样的价格选择:-

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return priceArray.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "stickCell", for: indexPath) as! StcikCell
    cell.priceLabel.text = "\(priceArray[0]) - \(priceArray[1])"
    return cell
}

但问题是我是否会使用这个:

cell.priceLabel.text = "\(priceArray[0]) - \(priceArray[1])" 

我只会得到 tableView 中的第一个和第二个值,但我真正想要的是在第一行我想得到 0 - 200 然后在第二行 200 - 400 第三个 400 - 600 等等,直到我得到 800 - 1000 的组合。我怎样才能做到这一点。请帮忙?

最佳答案

您需要使用 indexPath.row 来索引 cellForRowAt 中的 priceArray 并且还需要修改 numberOfRowsInSection 因为价格范围少于 priceArray 中的元素数量。

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

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "stickCell", for: indexPath) as! StcikCell
    cell.priceLabel.text = "\(priceArray[indexPath.row]) - \(priceArray[indexPath.row+1])"
    return cell
}

关于ios - 如何快速组合数组中的元素并显示在tableView上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53278083/

相关文章:

ios - 如何让 UIButton 宣布双击语音?

当 WiFi 处于事件状态时,iOS 可达性报告没有 WiFi

java - 快速排序整数数组的数组

iOS : How to check if date-time selected is valid time during day light savings?

ios - SwiftUI:Spacer 在 ScrollView 中不起作用

ios - 在 iOS5 中打开原生 map 应用

ios - View Controller 之间的 TableView 单元格操作

ios - 更改 tableView 中所有单元格的所有对象的 bool 状态

arrays - 当屏幕上的数据正常时,获取 "System.Collections.Generic.List` 1[System.String]"在 CSV 文件导出中

ios - 如何使 UICollectionView 单元格具有圆角和阴影?