ios - UITableView 在每个单元格中显示数组中的最后一项

标签 ios arrays swift uitableview struct

我正在使用相同结构的一组实例来填充一个 TableView ,但我对每个单元格中显示的数组中的最后一项感到困惑。

class RoutesViewController: UIViewController, UITableViewDataSource {

@IBOutlet weak var routesTableView: UITableView!


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

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

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let routeCell = routesTableView.dequeueReusableCell(withIdentifier: "routeCell") as! RouteTableViewCell



    for Flight in type1UnownedRoutesArray {
        routeCell.originLabel.text = "Origin:          \(Flight.origin)"
        routeCell.destinationLabel.text = "Destination: \(Flight.destination)"
        routeCell.priceLabel.text = "Price: $\(Flight.popularity)"
    }
  return routeCell
}

结构本身:

struct Flight {

var origin: String
var destination: String
var mileage: Int
var popularity: Int
var isOwned: Bool

}

如果我在 for Flight in type1UnownedRoutesArray 之后添加 [indexPath.row] 我会得到 Type Flight does not conform to protocol Sequence

在此先感谢您的帮助。

最佳答案

问题的根源是您的 cellForRow 方法中的这个问题,您正在遍历数组中的所有航类对象,当然最后一个值保留在您的单元格中,因此您需要替换这个

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let routeCell = routesTableView.dequeueReusableCell(withIdentifier: "routeCell") as! RouteTableViewCell

    for Flight in type1UnownedRoutesArray {
        routeCell.originLabel.text = "Origin:          \(Flight.origin)"
        routeCell.destinationLabel.text = "Destination: \(Flight.destination)"
        routeCell.priceLabel.text = "Price: $\(Flight.popularity)"
    }
  return routeCell
}

通过这个

   func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
   let routeCell = routesTableView.dequeueReusableCell(withIdentifier: "routeCell") as! RouteTableViewCell

    let flight = type1UnownedRoutesArray[indexPath.row]
    routeCell.originLabel.text = "Origin:          \(flight.origin)"
    routeCell.destinationLabel.text = "Destination: \(flight.destination)"
    routeCell.priceLabel.text = "Price: $\(flight.popularity)"
 }

希望对你有帮助

关于ios - UITableView 在每个单元格中显示数组中的最后一项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45684674/

相关文章:

ios - 无法在共享扩展中从 Twitter 应用加载图像

ios - 在 uitableviewcell swift 中加载 tableview

ios - 如何使用 ARKit ARSKViewDelegate 渲染 jpg 图像?

ios - 具有可达性的连接状态

javascript - 这个没有运算符的 "if"是如何工作的?

arrays - 掉落(其中 : {}) remove(where: {}) function in Swift?

ios - 如何创建一个随机的 if else 语句 swift 3

ios - 多个 UIViews,传递方法

ios - `indexOf` 抛出 "Object type does not match RLMResults"异常

c - 为什么我的合并函数输出一个无序的数组?