我正在使用相同结构的一组实例来填充一个 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/