6

i have a question about uitableview.i have a fruits list in uitableview and a filter button in right side navigation bar. how we can sort a fruits list when we click filter button. what should i do in filterList function. below is code.please look it.

/* Fruit.swift */

import Foundation

class Fruit {
    var fruitName = ""

    init(fruitName: String) { self.fruitName = fruitName }

}


class FruitsListViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    @IBOutlet var fruitList: UITableView!

    @IBOutlet var filterItem: UIBarButtonItem!

    var fruitArr:[Fruit] = Fruit

    override func viewDidLoad() {
        super.viewDidLoad()

        var barButton = UIBarButtonItem(title: "Filter", style: .Plain, target: self, action:"filterList") 
        self.navigationItem.rightBarButtonItem = barButton

        var fruits1 = Fruit(fruitName: "Apple" as String) 
        var fruits2 = Fruit(fruitName: "Mango" as String) 
        var fruits3 = Fruit(fruitName: "Banana" as String) 
        var fruits4 = Fruit(fruitName: "Orange" as String)

        fruitArr.append(fruits1)
        fruitArr.append(fruits2) 
        fruitArr.append(fruits3) 
        fruitArr.append(fruits4)
        }

    func filterList() {/* ? */}

    override func didReceiveMemoryWarning() {
          super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated.
     }

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

        func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
          let cell:ShowFruitCustomCellTableViewCell = tableView.dequeueReusableCellWithIdentifier('FruitCell') as ShowFruitCustomCellTableViewCell
          let fruit = fruitArr[indexPath.row] cell.setCell(fruit.fruitName) return cell
    }
    }
}
Maxim Shoustin
  • 77,483
  • 27
  • 203
  • 225
Viju
  • 427
  • 1
  • 9
  • 16
  • I've added code formatting but please consider formatting your code to a more readable format – Benjamin Gruenbaum Sep 21 '14 at 14:15
  • 1
    possible duplicate of [Swift how to sort array of custom objects by property value](http://stackoverflow.com/questions/24130026/swift-how-to-sort-array-of-custom-objects-by-property-value) – David Berry Sep 21 '14 at 18:43

6 Answers6

26

Well, just like it sounds - you'd filter the list:

func filterList() { // should probably be called sort and not filter
    fruitArr.sorted() { $0.fruitName > $1.fruitName } // sort the fruit by name
    fruitList.reloadData(); // notify the table view the data has changed
}

If you just want to reverse the items rather than actually sort them (to toggle the order) you can perform a fruitArr.reverse() instead of sorting.

Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504
3

Swift 3+

you can use .sorted() and .lowercased() (with string properties) to sort a-z, by default .sorted and .sort sort by A-z.

    //Prints Names A-z (0-9 then A-Z then a-z)
    fruitArr.sorted() { $0.fruitName > $1.fruitName }
    //prints  '000', 'Watermelon', 'apple'

    //Prints Name in alphabetical order.
    fruitArr.sorted() { $0.fruitName.lowercased() > $1.fruitName.lowercased() }
    //prints '000', 'apple', 'Watermelon'

See documentation for .sorted()

RLoniello
  • 2,309
  • 2
  • 19
  • 26
0

This is how I make a tableView descend rather than ascend. I do use a segue for the Tableview's loading and passing of data.

 // pass some data to the tableViewController in descending order
    override func prepare(for segue: UIStoryboardSegue, sender: Any?)
    {
        if segue.destination is TableViewController
        {
            let vc = segue.destination as? TableViewController
            vc?.passedData   = pointEntryArray.reversed()
            vc?.passedData01 = dataCenterArray.reversed()
        }
    }

hth

AB Murphy
  • 51
  • 4
0

How about this:

placed in viewDidLoad or cellForRow, before appending data.

fruitArr.sort()
kyun
  • 9,710
  • 9
  • 31
  • 66
wwarren07
  • 17
  • 9
  • `cellForRow` gets called for every cell in the `UITableView`. This would effectively sort the list many times. Sort in `viewDidLoad` or when a button is clicked, but never in this method. – inexcitus Aug 09 '21 at 12:29
0

Its very easy using didSet:

var fruitArr = [Fruit]() {
   didSet {
      fruitArr = fruitArr.sorted(by: {  $0. fruitName < $1. fruitName })
   }
}
Ing. Ron
  • 2,005
  • 2
  • 17
  • 33
-4

The easiest way I use to add and sort element into an array is to add them at the index 0:

fruitArr.insert(fruits1, at: 0)
fruitArr.insert(fruits2, at: 0) 
fruitArr.insert(fruits3, at: 0)
fruitArr.insert(fruits4, at: 0)