如何解决Swift过滤器tableviewcell数组计数
我正在尝试在单元格中显示数据。我按布尔值和日期筛选了数组。 当我打印“ cell.title.Label.text”时,我得到了5个标签。 (您可以在我的代码中看到)。 3种标签文本颜色为红色,1种黑色和1种灰色。
我得到5个数据,但是3个数据是过去的时间。如何获得这3个数据作为Int(count)?
我的代码:
func tableView(_ tableView: UITableView,cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell",for: indexPath) as! RestCell
cell.titleLabel.text = titleArray[indexPath.row]
cell.docIdLabel.text = docIdArray[indexPath.row]
let isoDate = dateArray[indexPath.row]
let dateFormatter = DateFormatter()
dateFormatter.locale = NSLocale.current
dateFormatter.dateFormat = "dd.MM.yyyy HH:mm"
let date = dateFormatter.date(from:isoDate)!
let rowArrayValue = completedArray[indexPath.row]
if rowArrayValue == false {
cell.checkboxButton.setOn(false,animated: true)
if date < Date() {
cell.titleLabel.textColor = UIColor.red
cell.dateLabel.textColor = UIColor.red
print("Label Name is : \(cell.titleLabel.text!)")
//Label Name is : Test1
//Label Name is : Test2
//Label Name is : Test3
} else {
cell.titleLabel.textColor = UIColor.black
cell.dateLabel.textColor = UIColor.black
print("Label Name is : \(cell.titleLabel.text!)")
//Label Name is : Test4
}
} else {
cell.checkboxButton.setOn(true,animated: true)
cell.titleLabel.textColor = UIColor.gray
cell.dateLabel.textColor = UIColor.gray
print("Label Name is : \(cell.titleLabel.text!)")
//Label Name is : Test5
}
cell.buttonTapped = {
if cell.checkboxButton.on == true {
cell.checkboxButton.setOn(true,animated: true)
tableView.reloadData()
} else {
cell.checkboxButton.setOn(false,animated: true)
tableView.reloadData()
}
}
return cell
}
解决方法
在使用compare(_:)
获得的date
上使用 DateFormatter
过滤掉当前日期之前的日期,然后得到count
,
let pastDatesCount = dateArray.compactMap {(date) -> Date? in
let dateFormatter = DateFormatter()
dateFormatter.locale = NSLocale.current
dateFormatter.dateFormat = "dd.MM.yyyy HH:mm"
if let date = dateFormatter.date(from: date),date.compare(Date()) == .orderedAscending {
return date
}
return nil
}.count
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。