如何使用关系 Swift 显示 UITableView 3



看了很多帖子,但找不到解决我的情况的方法。

有实体天数,也有实体任务。每天可以有 0 个或多个任务。我需要在UITableView中显示特定日期的任务列表。

如何通过以下关系获取行数(任务(:

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
}

然后如何格式化单元格:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath)-> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "TodayCell", for: indexPath as IndexPath) as! TodayTableViewCell
let task = //how to get task?
cell.taskDescription?.text = task.descritpion            
return cell
}
创建自定义
  • 结构

    struct Schedule {
    let date : Date
    var tasks : [Task]
    }
    
  • 创建数据源数组

    var schedules = [Schedule]()
    
  • 获取按天排序的Day实体(到数组days

    (
  • 如果有一个或多个任务,则将项映射到自定义结构(简单代码,很可能您的属性不同(

    schedules.removeAll()
    for day in days {
    if !day.tasks.isEmpty {
    schedules.append(Schedule(date: day.date, tasks:day.tasks.allObjects as! [Task]))
    }
    }
    tableView.reloadData()
    
  • numberOfSections返回schedules.count

  • numberOfRows...返回schedules[section].tasks.count
  • IntitleForHeaderInSection返回schedules[section].date的字符串说明
  • cellForRow...获得单个任务

    let day = schedules[indexPath.section]
    let task = day.tasks[indexPath.row]
    

最新更新