感谢您将来的帮助!那是我的结构数组:
var malls: [Mall] = [
mall(name:"yagey", distance:""),
mall[name:"tigey", distance:"")
]
覆盖func viewDidLoad(){ super.viewDidLoad()
var mall = malls[index]
let mallLocate = CLLocation(latitude: mall.latitude, longitude: mall.longitude)
let distanceInMeters = mallLocate.distance(from: coords) / 1000
let distanceInMetersString = String(format: "%.1f", distanceInMeters)
for index in 0..<malls.count {
var mall = malls[index] // copy a mall value
mall.distance = distanceInMetersString // change the copy of mall
malls[index] = mall // put the updated mall back into the array
}
malls.sort() { $0.distance < $1.distance }
如何通过mall.distance对商场进行排序? 请帮助我,我无法理解错误:(
这是我的tableView
的tableView
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! EateriesTableViewCell
let mall = mallToDisplayAt(indexPath: indexPath)
let mallLocate = CLLocation(latitude: mall.latitude, longitude: mall.longitude)
print (mallLocate)
cell.distanceLabel.text = distanceInMetersString + "км"
return cell
}
答案 0 :(得分:0)
您必须先在viewdidload中对商城数组进行排序,例如在排序后重新加载您的tableviews数据
self.tableView.reloadData()
并且在你的单元格中,行将是这样的:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! EateriesTableViewCell
let mall = mallToDisplayAt(indexPath: indexPath.row)
let mallLocate = CLLocation(latitude: mall.latitude, longitude: mall.longitude)
print (mallLocate)
let distanceInMeters = mallLocate.distance(from: coords) / 1000
let distanceInMetersString = String(format: "%.1f", distanceInMeters)
cell.distanceLabel.text = distanceInMetersString + "км"
print (mall.distance)
return cell
}
答案 1 :(得分:0)
您的排序代码很好。把它放在委托方法之外。
在委托方法
中使用for循环有什么意义for index in 0..<malls.count {
var mall = malls[index] // copy a mall value
mall.distance = distanceInMetersString // change the copy of mall
malls[index] = mall // put the updated mall back into the array
}
这里设置数组distanceInMetersString中所有对象的距离属性。
如果您想要排序,请在tableView委托方法之外进行排序编码。并且删除上面提到的for循环。排序后只需重新加载tableview:)