如何从swift中的位置搜索重新排序collectionView中的可见单元格?

时间:2017-10-30 23:17:17

标签: swift swift3 uicollectionview core-location cllocationmanager

我正在使用MAPKit搜索附近的位置并将它们显示到collectionView控制器中。我设法做到了,效果很好。现在我试图过滤结果,只显示特定距离的结果。它工作但我无法使其正常工作:我通过为cellForRowAtIndexPath中不在距离内的单元格设置隐藏单元格来实现这一点。现在,collectionView显示了细胞之间的间隙,因为它们没有重新排列。我怎么能设法做到这一点?我将非常感谢一些帮助,因为我在很长一段时间内都在努力解决这个问题。 :)

这是我的cellForRowAtIndexPath:

    var matchingItems:[MKMapItem] = []
    var mapView: MKMapView? = nil

     func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "LocationCell", for: indexPath) as! LocationCell
        cell.contentView.backgroundColor = .white
        cell.layer.borderColor = UIColor(white: 0.5, alpha: 0.3).cgColor
        cell.layer.borderWidth = 0.3

        theIndex = indexPath.row

        let selectedItem = matchingItems[indexPath.row].placemark
        cell.itemName.text = selectedItem.name
        cell.itemAddress.text = parseAddress(selectedItem: selectedItem)

        //LOGIC: Current location - business location / transform into points / get distance in between
        let currentLocation = locationManager.location?.coordinate
        let currentUserLocation = CLLocation(latitude: (currentLocation?.latitude)!, longitude: (currentLocation?.longitude)!)
        let locationMapPoint = MKMapPointForCoordinate(currentUserLocation.coordinate)

        let coordinates = selectedItem.coordinate
        let itemsMapPoint = MKMapPointForCoordinate(coordinates)

        let distance = MKMetersBetweenMapPoints(locationMapPoint, itemsMapPoint)

        let distanceInMiles = (distance / 1000) / 1.6
        cell.itemMiles.text = "\(String(format: "%.1f", distanceInMiles)) miles"

        if distanceInMiles <= setRadius {
            cell.isHidden = false

            let visibleRows = collectionView.indexPathsForVisibleItems.count
            print("Visible: \(visibleRows)")


        } else if distanceInMiles > setRadius {
            cell.isHidden = true

            if cell.isHidden {
                let matches = 0
                if matches == indexPath.row {
                    //matchingItems.remove(at: matches)
                    print("Hidden at: \(matches)")
                    //collectionView.reloadData()
                }

            }

        }

        if matchingItems.isEmpty {
            print("all is empty....")
        } else {

        }
        return cell
    }

这是我得到的错误: (在此示例中,单元格0和5显示其余部分隐藏超过半径) In this example cell 0 and 5 is displayed the rest are hidden being more than the radius

0 个答案:

没有答案