问题
I have a UITableView, Where I'm loading address from Geocoder by latlng. when I scroll down tableview first time all is fine & working in good manner. But Problem is when I'm scroll up then all address lost their cell. I mean the address of 5th cell now showing on 1st cell.
This is my cellForRowAt tableview method
let cell = self.mytableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! HomeCell
let position = indexPath.row
let data = mVehicleList[position]
getAddress(lat: data.latitude.toD(), lng: data.longitude.toD(), text: cell.lbAddress)
// getAddress is extenstion of ViewCOnroller which is give addres of latlng
This my getAddress(lat,lng,label) extension
extension UIViewController {
func getAddress(lat:Double,lng :Double, text : UILabel)
{
let location = CLLocation(latitude: lat, longitude: lng)
CLGeocoder().reverseGeocodeLocation(location, completionHandler: {(placemarks, error) -> Void in
if(placemarks != nil){
if placemarks!.count > 0 {
let pm = placemarks![0]
if(pm.subLocality != nil && pm.subAdministrativeArea != nil)
{
text.text = pm.subLocality!+" "+pm.subAdministrativeArea!
}else{
guard let addressDict = placemarks?[0].addressDictionary else {
return
}
if let formattedAddress = addressDict["FormattedAddressLines"] as? [String] {
text.text = formattedAddress.joined(separator: ", ")
}
}
}else{
text.text = "No address found"
}
}
}) } }
回答1:
This is because of dequeuing
if let addr = data.addressText {
cell.lbAddress.text = addr
}
else {
getAddress(indexPath.row,lat: data.latitude.toD(), lng: data.longitude.toD(), text: cell.lbAddress)
}
I suggest to geocode the location and alter the model with the retrieved address , then reload the table/indexPath , and that will save you from getting the same address again and again when you scroll the table , just check the model's location if nil then start the geocode , if not then assign it to the label
func getAddress(_ index:Int,lat:Double,lng :Double, text : UILabel) {
///
mVehicleList[index].addressText = formattedAddress.joined(separator: ", ")
// reload table/index
}
class model {
var state:State = .none
func geocode(){
gurad state == .none else { return }
state = .geocoding
CLGeocoder().reverseGeocodeLocation//// {
state = .geocoded // if success
}
}
}
enum State {
case geocoding,gecoded,none
}
来源:https://stackoverflow.com/questions/53867778/uitableviewcell-updating-wrong-cell-label-text