首页 > 解决方案 > 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
}

标签: arraysswiftuitableview

解决方案


使用获取compare(_:)dateusingDateFormatter过滤掉当前日期之前的日期,然后得到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

推荐阅读