ios - SWIFT:排序 TableView 并将数据传递给第二个 viewController

标签 ios swift uitableview segue

我有一个非常有趣的问题:

我有两个 View Controller :FirstViewController 和 SecondViewController。

FirstViewController 中有table view。

有一个按钮可以对表格中的行进行排序。

View Controller 之间存在 segue。

//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"]!)

        }

假设我们在表格中有三行不同的银行名称:Bank1、Bank2、Bank3。排序功能运行良好 - 它更新了我的表格。假设排序后我们有新序列:Bank3、Bank2、Bank1。

所以毕竟 - 问题是当我使用 segue 将值导出到 secondViewController 时。如果我不使用排序,它工作得很好。但如果我这样做,它会像排序前那样传输值。

例如不排序,如果我按顶行,它将导出 bank1。

但是。排序后我们在顶行有 Bank3,但它仍然将 Bank1 传输到 secondViewController。

任何人都可以解释我错过了什么吗? 谢谢。

最佳答案

changeSorting 中,您似乎更新了一个名为 arrayOfBanks 的数组。我假设这个数组是你的数据源。但是在 prepareForSegue 中,您使用所选行的索引路径来访问名为 bankDict 的字典。这个字典没有被排序方法影响,所以它的顺序和以前一样。

关于ios - SWIFT:排序 TableView 并将数据传递给第二个 viewController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36411759/

相关文章:

ios - UILabel 根据文字大小自动调整大小

ios - 为多个 UIAlertController 分派(dispatch) asyncAfter

ios - UIGraphicsGetCurrentContext 没有出现在 UIView 中

iphone - UITableView 在动画过程中崩溃,已找到解决方案,但没有找到根本原因,想知道为什么?

ios - 在 iOS 上使用 MDCBottomNavigationBar 切换 View Controller

ios - 将 UIImage 创建为带颜色的边框

ios - 使用 UserDefaults 相互替换值

ios - tableFooterView 属性中的 UIView 不适合 UITabelView 的 ScrollView

ios - 应用程序切换期间 UITableView 分隔符闪烁

objective-c - UIView 中的圆柱形外观渐变