简体   繁体   中英

SWIFT: sorting TableView and pass data to second viewController

I have very interesting problem:

I have two view controllers: FirstViewController and SecondViewController.

There is table view in FirstViewController.

There is a button to order rows in table.

There is segue between view controllers.

//MARK: Sorting function:
func changeSorting(buttonTag: Int) {

        let button = self.view.viewWithTag(buttonTag) as? UIButton
        let buttonName = (button?.currentTitle)! as String

        //Apply Sorting to table:

            arrayOfBanks.sortInPlace {
                item1, item2 in

                let val1 = item1["sellRate"] as! Double
                let val2 = item2["sellRate"] as! Double

                if buttonName == "0-9⬇︎" {
                    return val1 > val2
                } else  {
                    return val2 > val1
                }
            }
         self.tableView.reloadData()

}

    //MARK: Navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if segue.identifier == "showCalculator" {
            let viewController = segue.destinationViewController as! SecondViewController
            let indexPath = tableView.indexPathForSelectedRow?.row

            print(indexPath!)

            viewController.bn = self.bankDict[indexPath!]["bankName"]! as! String
            viewController.cn = self.bankDict[indexPath!]["currencyName"]! as! String
            viewController.br = String(self.bankDict[indexPath!]["sellRate"]!)
            viewController.sr = String(self.bankDict[indexPath!]["buyRate"]!)

        }

Imagine that we have three rows in table with different bank names: Bank1, Bank2, Bank3. Sorting functions works well - it updates my table. Lets say after sorting we have new sequence: Bank3, Bank2, Bank1.

So after all - the problem is when I use segue to export values to secondViewController. It works just fine if I don't use sorting. But If I do, it transfers values as it would be before sorting.

EG without sorting if I press top row it would export bank1.

but. after sorting we have Bank3 on the top row, but it still transfers Bank1 to secondViewController.

Can anybody explain what I am missing? Thanks.

It looks like in changeSorting you update an array called arrayOfBanks . I assume this array is your data source. But in prepareForSegue you use the index path of the selected row to access a dictionary called bankDict . This dictionary was not touched by the sorting method, so it's ordering would be the same as before.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM