我有一个这样的数组:-
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/