按距离排序Tableview,Swift

时间:2017-12-04 14:31:03

标签: swift sorting tableview distance

我在编码方面很陌生并且目前陷入困境,我无法找到可行的解决方案,所以这是我的问题,希望有人能够帮助我。

我想要达到的目的是按距离最近的餐厅对数据进行排序。我可以计算距离并在列表视图中显示它,但不幸的是我无法弄清楚如何按距离对列表进行排序。我假设它是由于我计算距离,然后返回配置的单元格。 (我已经能够按名称,小时等对餐馆进行分类)

我在我的viewdidload中从firebase中取出restaurantdata,将其添加到数组中,然后重新加载我的tableview。

下面是我计算距离的代码。 非常感谢任何帮助,如果我需要发布更多信息或代码,请告诉我。

  • 的Nik

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard let cell = tableView.dequeueReusableCell(withIdentifier: "restaurantCell", for: indexPath) as? RestaurantCell else { return UITableViewCell() }
        cell.selectionStyle = .none
        let restaurantInfo = restaurantDataArray[indexPath.row]
    
        let coordinate0 = CLLocation(latitude: RestaurationerVC.lat, longitude: RestaurationerVC.lon)
        let coordinate1 = CLLocation(latitude: restaurantInfo.latitude, longitude: restaurantInfo.longitude)
        let mulitplier = pow(10.0, 1.0)
        let distanceInKm = (coordinate0.distance(from: coordinate1)) / 1000
        let distanceRounded = round(distanceInKm * mulitplier) / mulitplier
    
        cell.configureCell(title: restaurantInfo.title!, restaurantImg: restaurantInfo.subtitle!, distance: "\(distanceRounded) Km", hours: restaurantInfo.hours, restaurantType: restaurantInfo.restaurantType, photo: restaurantInfo.photo)
    
        return cell
    }
    

1 个答案:

答案 0 :(得分:1)

我建议您对从Firebase获取的数组进行排序,然后在tableView中重新加载数据。尝试对tableview本身进行排序是非常低效的。当你说你在返回可以改变的单元格之前计算距离,以便在yuor datamodel中计算它。尝试创建一个表示一个单元格数据的结构(让我们称之为struct Restaurant)。这可以包含所有计算数据的变量。然后你可以将它们全部放在restaurants = Restaurant中,你可以按距离实现排序,然后在tableview cellforrowat indexpath函数中使用这个数组。