ChallengerGuy
ChallengerGuy

Reputation: 2395

Swift 2 TableView Sorting

I have an iOS project I'm working on in Xcode 7 using Swift 2. I have an array called details with a dictionary which includes a String and an Int value. The Int is called cellOrder in the Class and the idea is to sort the details array in a TableView with a sort based on the cellOrder Int value.

The array shows the String values which are names. I looked here to try and implement this into my project with no success.

Here is my array:

// Array of data for the TableView
var details = [ProjectDetails]()

Here is my TableView Code:

func numberOfSectionsInTableView(tableView: UITableView) -> Int {

    return 1

}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return details.count

}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell

    cell.textLabel!.text = details[indexPath.row]        

    return cell

}

How do I do the sort and where would I put the code, ViewDidLoad() or maybe cellForRowAtIndexPath?

UPDATE:

My ViewDidLoad():

override func viewDidLoad() {
    super.viewDidLoad()

    // TableView Sorting
    details.sortInPlace({$0.cellOrder < $1.cellOrder})

    tableView.delegate = self

    ...

}

Update 2:

My ProjectDetails class for the array data is:

import UIKit

class ProjectDetails: NSObject, NSCoding {

    // MARK: Properties

    var fileName: String
    var cellOrder: Int

    ...

}

Upvotes: 2

Views: 4897

Answers (2)

diatrevolo
diatrevolo

Reputation: 2822

To sort the array you would just do details.sortInPlace({$0.cellOrder < $1.cellOrder}) in viewDidLoad, or you could use details.sort({$0.cellOrder < $1.cellOrder})[indexPath.row] in cellForRowAtIndexPath, but that could prove dangerous if you do not keep track of your array.

One will sort the array in place, one will return a sorted immutable array.

If you insist on sorting immutably (has its pros and cons beyond this scope) assign it to another array and use that in your logic.

Upvotes: 3

Ulysses
Ulysses

Reputation: 2317

You must sort the itens in this array details[], after that, you can call tableView.reloadData() to reload the info.

In the cellForRowAtIndexPath you must just take the data to fill the cell, so NO SORT THERE!

Sort anywhere else, before call the function to reload.

Upvotes: 1

Related Questions