【问题标题】:sort tableViewCells by numbers inside a label按标签内的数字对 tableViewCells 进行排序
【发布时间】:2019-11-30 14:39:52
【问题描述】:

我尝试按标签内的数字对 tableViewCells 进行排序,因此标签中包含最高数字的单元格应该排在最后,反之亦然。 我尝试了以下不同的解决方案,但它根本不起作用,它也没有显示任何错误代码

我不知道是只是一个小错误还是完全错误,但如果是这样,我希望你知道一个完全不同的方法来解决它。

表格视图:

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    // download jobs
    jobsRef.observe(.value, with: { (snapshot) in
        self.jobs.removeAll()

        for child in snapshot.children {
            let childSnapshot = child as! DataSnapshot
            let job = Job(snapshot: childSnapshot)
            print(job)
            self.jobs.insert(job, at: 0)
        }
        filterLocation()
        self.tableView.reloadData()
    })
}

var jobArr = JobTableViewCell.jobDistance!.jobArr
func filterLocation() {
    jobArr.sort() { $0.distance.text > $1.distance.text}
}

TableViewCell:

@IBOutlet weak var distance: UILabel!
static var jobDistance: JobTableViewCell?
var jobArr = [JobTableViewCell.jobDistance!.distance.text]

override func layoutSubviews() {
    super.layoutSubviews()
    JobTableViewCell.jobDistance = self
}

【问题讨论】:

  • 最好先对数据源进行排序,然后重新加载tableView
  • 我建议不要对单元格进行排序,而是对数据源进行排序。让表格视图负责渲染您的单元格。
  • 你在哪里打电话filterLocation
  • @Sh_Khan 我在 viewDidAppear 中调用它,在重新加载 tableview 之前(也用新代码更新了我的问题)

标签: ios swift uitableview uilabel


【解决方案1】:

让我们查看苹果文档以获取表格视图https://developer.apple.com/documentation/uikit/uitableviewdatasource

正如它所说的有方法:

func tableView(UITableView, cellForRowAt: IndexPath) -> UITableViewCell

我们可以把它读成“给我[UITableView] cell[-> UITableViewCell] for this index[cellForRowAt]”

所以我们只需要将我们的数据源映射到 tableview 索引:

例如

我们有字符串的数据源数组

var dataSource = ["String", "Very long string", "Str"]

排序...

> ["Str", "String", "Very long string"]

然后将我们的数据提供给单元格(您的表格视图必须符合 UITableViewDataSource 协议)

// Provide a cell object for each row.
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
   // Fetch a cell of the appropriate type.
   let cell = tableView.dequeueReusableCell(withIdentifier: "cellTypeIdentifier", for: indexPath)

   // Configure the cell’s contents.
   cell.textLabel!.text = dataSource[indexPath]

   return cell
}

【讨论】:

    【解决方案2】:

    问题是你排序另一个数组jobArr

    jobArr.sort() { $0.distance.text > $1.distance.text}
    

    并将值附加到另一个jobs

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-18
      • 1970-01-01
      • 1970-01-01
      • 2011-05-16
      相关资源
      最近更新 更多