【问题标题】:How to display UITableView with Relationship Swift 3如何使用关系 Swift 3 显示 UITableView
【发布时间】:2017-08-07 09:57:46
【问题描述】:

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

有实体Days,有实体Tasks。每天可以有 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
    }

【问题讨论】:

  • 您不获取行数,您需要使用过滤结果创建数据源并将其计数传递给行数
  • 你是如何声明 tasks 和 days 变量的?
  • 你应该有一个包含任务对象的数组,然后你可以通过这种方式选择一个任务。让 task = tasks[indexPath.row] ,行数应该返回 tasks.count

标签: ios uitableview swift3


【解决方案1】:
  • 创建自定义结构

    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
  • titleForHeaderInSection中返回schedules[section].date的字符串描述
  • cellForRow...获取单个任务

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-30
    相关资源
    最近更新 更多