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
}
}
}
To sort the array we use the sort() function. This function is used to sort the elements of the array in a specified order either in ascending order or in descending order. It uses the “>” operator to sort the array in descending order and the “<” operator to sort the array in ascending order.
Strings in Swift conform to the Comparable protocol, so the names are sorted in ascending order according to the less-than operator ( < ). To sort the elements of your collection in descending order, pass the greater-than operator ( > ) to the sort(by:) method.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With