arrays - Swift过滤tableviewcell数组计数
问题描述
我正在尝试在单元格中显示数据。我按布尔值和日期过滤了数组。当我打印“cell.titleLabel.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
usingDateFormatter
过滤掉当前日期之前的日期,然后得到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
推荐阅读
- css - 在绘图生成的散点图矩阵周围放置边框的正确 CSS 语法是什么?
- java - Java Jackson Polymorphic - 接口字段匹配导致重复的字段名称
- php - jquery如何在邮件发送后隐藏元素
- python - Python ibm_db 异常:[IBM][CLI Driver] SQL4917N 选项数组中的元素“SQLE_CLIENT_INFO_WRKSTNNAME”无效。SQLCODE=-4917
- powershell - Powershell 加载二进制模块
- python - 无法在 Windows 10 上安装 Python 3.7.4 的 pip
- html - 使用 GreaseMonkey 从网站隐藏 DIV 的问题
- javascript - Javascript保持焦点并点击元素
- html - 将鼠标悬停在文本上时出现“淡入”效果的问题
- selenium - 金牛座代理问题