/ / Ordina UITableView con doppio - swift, firebase, firebase-database

Ordina UITableView con double - swift, firebase, firebase-database

Sto provando a creare un UITableView che è ordinatodalla dimensione del valore di latitudine trovato nel database. Sebbene le mie celle UITable visualizzino tutti i nomi dei negozi e la console stampi la latitudine, non riesco ancora a capire come ordinare le celle in base al loro valore di latitudine. Ecco il mio codice attuale:

@IBOutlet weak var nearbyTableView: UITableView!
var myList: [String] = []
var handle:DatabaseHandle?
var ref:DatabaseReference?


func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return myList.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

let cell = UITableViewCell(style: .default, reuseIdentifier: "cell")
var (cellName) = myList[indexPath.row]
cell.textLabel?.text = cellName
return cell

}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = UITableViewCell(style: .default, reuseIdentifier: "cell")
var (cellName) = myList[indexPath.row]

let viewController = self.storyboard?.instantiateViewController(withIdentifier: "Home2") as! ShopViewController
viewController.name = cellName
self.present(viewController, animated: true, completion: nil)
navigationController?.pushViewController(viewController, animated: true)

print("row(indexPath.row)")
print("name: (cellName)")
}




override func viewDidLoad() {
super.viewDidLoad()

let messageDB = Database.database().reference().child("shops")

messageDB.observe(.childAdded, with: { snapshot in

let snapshotValue = snapshot.value as! NSDictionary
let text = snapshotValue["name"] as! String
let lat = snapshotValue["lat"] as! Double

print(text)
print(lat)

self.myList.append(text)
self.nearbyTableView.reloadData()
})

}

}

risposte:

0 per risposta № 1

Il problema sembra essere che stai aggiungendoogni nuovo elemento alla fine dell'origine dati (myList). Un'opzione possibile sarebbe quella di modificare myList in modo che contenga anche il valore lat (ad esempio utilizzando una tupla (String, Double) e inserire ogni nuovo elemento prima del primo elemento esistente che ha lat maggiore del proprio. Quindi, ad esempio, se tu avessi una myList esistente in questo modo

var myList: [(String, Double)] = [("Name1", 0.1), ("Name2", 0.2), ("Name4", 0.4)]

quindi è possibile aggiungere un nuovo elemento cercando l'indice appropriato e inserendo tale indice, in questo modo

let myNewElement: (String, Double) = ("Name3", 0.3)

if let insertionIndex = myList.index(where: {myNewElement.1 <= $0.1}) {

myList.insert(myNewElement, at: insertionIndex)
}

// myList = [("Name1", 0.1), ("Name2", 0.2), ("Name3", 0.3), ("Name4", 0.4)]

dopo questo, il compito nel tuo cellForRowAt: dovrebbe cambiare, in questo modo:

cell.textLabel?.text = myList[indexPath.row].0