我正在使用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
}