1

I added texts into tableViewCell by using a textfield, and the order of words entered in the cell on the top of a tableView was non-alphabetical. How does it become alphabetically ordered? Is there any built-in method to do this, or do I write a method? Thank you!

@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var myTextField: UITextField!
var stringArray = [String]()


override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

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

func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return stringArray.count
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = self.tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell

    cell.textLabel?.text = stringArray[indexPath.row]
    return cell
}

func textFieldShouldReturn(textField: UITextField) -> Bool {
    return true
}

@IBAction func AddButton(sender: UIButton) {
    stringArray.append(myTextField.text)
    myTextField.text = nil
    myTextField.resignFirstResponder()
    tableView.reloadData()
}

}

Ryohei Arai
  • 121
  • 1
  • 7

2 Answers2

0

The UITableView is just showing you the same strings that are in your array. You are using the append method which always adds the items to the end of the array. Instead you should sort your array and the data shown in the UITableView will be sorted.

Arrays have sort for which you provide the comparison closure. Either you make a method for sorting and pass it to the sort as the isOrderedBefore parameter, or you could do it this way.

stringArray.sort(){ $0 < $1 }

where $0 and $1 are the first and second parameters that will be compared.

hannad
  • 822
  • 4
  • 18
  • You're welcome. If it worked for you, please mark the question as answered so others don't think this is still an open question :) – hannad Dec 16 '15 at 10:17
0

For a Finder like sort order you can use localizedStandardCompare.

    stringArray.sortInPlace { (x, y) -> Bool in
        return x.localizedStandardCompare(y) == NSComparisonResult.OrderedAscending
    }

Also to add onto @hannad's answer, you should use sortInPlace to ensure stringArray is sorted. Else use something like

    sortedArray = stringArray.sort(){ $0 < $1 }
UditS
  • 1,936
  • 17
  • 37