Home > Blockchain >  Put specific cells on top of the tableView
Put specific cells on top of the tableView

Time:02-08

How can i put specific cells to show on top of the tableView? , For example I have 10 cells which 5 of them have red color and other 5 have green and I want to show the top 5 ones with the green colors on top and the other 5 with red below them?

I didn't find any resources so I decided to get advise from the dear SO community.

Code:

extension MonitorimiViewController: UITableViewDelegate, UITableViewDataSource{

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


func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    guard let cell = tableView.dequeueReusableCell(withIdentifier: "monitorimiCell", for: indexPath) as? MyCustomCell1 else {return UITableViewCell()}
    let currentVechicle = listOfVechicle[indexPath.row]

    cell.veturaOutlet.text = currentVechicle.Plate
    cell.shpejtsiaAktualeOutlet.text = currentVechicle.Speed!
    cell.perditsuarOutlet.text = "\(currentVechicle.LastCommunicationDate!.convertToDisplayForm())"
    cell.pasagjereOutlet.text = "\(currentVechicle.Passengers!) Person/a"
    cell.vozitesiOutlet.text = "\(currentVechicle.Driver!)"

    switch currentVechicle.Status {
    case 1:
        cell.colorsImageView.backgroundColor = .green
    case 2:
        cell.colorsImageView.backgroundColor = .red
    case 3:
        cell.colorsImageView.backgroundColor = .black
    case 4:
        cell.colorsImageView.backgroundColor = .orange
    default: break
    }

    return cell

So from the currentVechicle.Status I need the case 1 to show on top then the rest.

CodePudding user response:

You do not show how your data is structured so you will have to edit my code to fit your needs. After you set you data, call this function to sort it by whichever UIColor you would like. Then call tableView.reloadData()

var data: [[String: [String: Any]]] = [["mazda": ["color": UIColor.green]],["honda": ["color": UIColor.red]]]

func SortVehicleDataWithPriorityColor(_ color: UIColor) {
    var newData = [[[String: [String: Any]]](), [[String: [String: Any]]]()]
    data.map {
        if $0.first!.value["color"] as? UIColor == color { newData[0].append($0) }
        else { newData[1].append($0) }
    }
    data = newData[0]   newData[1]
}

SortVehicleDataWithPriorityColor(.green)

The key thing here is in the .map {} part. $0 means THIS element in the list, much like how name in for name in names {} would mean the current name in the list.

  •  Tags:  
  • Related