我如何基于与当前位置的距离对数组进行排序并在tableview中显示。当我使用排序时,没有得到任何正确的结果,我获得了具有随机距离的数组。任何人都可以指导我解决这个问题

最佳答案

根据与当前位置的距离以最佳方式对位置进行排序,将具有结构形式的位置点

struct LocationPoints {
    var latitude: CLLocationDegrees
    var longitude: CLLocationDegrees

    func distance(to currentLocation: CLLocation) -> CLLocationDistance {
        return CLLocation(latitude: self.latitude, longitude: self.longitude).distance(from: currentLocation)
    }
}


假设您有一个具有经度和纬度的LocationPoints数组

var coordinates: [LocationPoints] = []
            coordinates.append(LocationPoints(latitude: Double(25), longitude: Double(24)))
                coordinates.append( LocationPoints(latitude: Double(23), longitude: Double(22)))


排序功能

    coordinates = sortLocationsWithCurrentLocation(locations: coordinates, currentLocation: CLLocation(latitude: Double(20), longitude: Double(21)))




    func sortLocationsWithCurrentLocation(locations:[LocationPoints],currentLocation:CLLocation) -> [LocationPoints] {
//set here current position as current location
            let currentPosition : CLLocation = CLLocation(latitude: 30, longitude: 24)
            let sortedLocations = locations.sorted(by: { (point1 : LocationPoints, point2 :LocationPoints) -> Bool in
                if point1.distance(to: currentPosition) < point2.distance(to: currentPosition)
                {
                    return true
                }
               return false
            })
            return sortedLocations
        }

关于ios - 如何设置UITabBar背景图像更改?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45050640/

10-14 20:36
查看更多