【问题标题】:How to sort cells in tableView?如何对tableView中的单元格进行排序?
【发布时间】:2018-02-08 15:56:34
【问题描述】:

如何对tableView中的单元格进行排序?


我有结构和数组:

struct Converter {
        let title: String
        let kf: Double
    }

    let converterAtmo = [
        Converter(title: "Атмосферы", kf: 1),
        Converter(title: "Бары", kf: 365.2422),
        Converter(title: "Мм.рт.ст.", kf: 11.999998),
        Converter(title: "Паскали", kf: 525948.77),
        Converter(title: "Фунт./кв.дюйм", kf: 52.177457)]

CellAtRow函数中:

let cell1 = tableView.dequeueReusableCell(withIdentifier: "resultCell") as! resultTableViewCell

            let item = converterAtmo[indexPath.row]

            cell1.nameResult.text = item.title
            cell1.labelResult.text = String(item.kf * atmosfera)


            return cell1

最后是@IBAction:

 @IBAction func sortAlphabet(_ sender: Any) {

        let itemSort = converterAtmo

        itemSort.sorted { $0.title < $1.title }

        self.tableView2.reloadData()

    }

但它不起作用......

我的问题是什么?

【问题讨论】:

  • 这在您的代码之外不容易重现。

标签: ios swift uitableview sorting uilabel


【解决方案1】:

首先,您必须将converterAtmo 声明为var 而不是let,以便您可以修改它。

然后替换:

itemSort.sorted { $0.title < $1.title }

与:

self.converterAtmo = itemSort.sorted { $0.title < $1.title }

在您当前的实现中,您对模型的副本进行排序(itemSort 只是您的self.converterAtmo 的副本),因此它对 tableView 后面的模型没有任何影响。您需要将该排序后的数组设置回 tableView 数据模型。

或者更好,你可以使用这个:

@IBAction func sortAlphabet(_ sender: Any) {
    // `sort` method will sort the converterAtmo (`sorted` method leaves the original 
    // array untouched and returns a sorted copy)
    self.converterAtmo.sort { $0.title < $1.title }
    self.tableView2.reloadData()
}

【讨论】:

    【解决方案2】:

    在:

    let itemSort = converterAtmo
    itemSort.sorted { $0.title < $1.title }
    

    您实际上并没有对数组进行排序。您正在将其复制到“itemSort”中,而没有对其进行任何操作。

    【讨论】:

      猜你喜欢
      • 2015-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多