ios - 分割 UITableView 单元格

标签 ios arrays swift uitableview firebase

我试图将我的 tableview 单元格组织成列表中项目元素的部分 (dueTime)。 Firebase 是我的后端,每个项目都有一个名为 dueTime 的子节点,其中包含时间字符串。我已经创建了这些部分并让它们显示出来,但我需要将实际项目分成它们。目前,当我运行我的代码时,所有显示的都是部分。

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        let tasksRef = ref.childByAppendingPath("tasks")
        tasksRef.observeSingleEventOfType(.Value, withBlock: {snapshot in
            var dueTimesArray = [String]()
            for task in snapshot.children.allObjects as! [FDataSnapshot] {
                let times = task.value["dueTime"] as! String
                dueTimesArray.append(times)
            }
            self.sectionTimes = dueTimesArray
        })
        let uniqueSectionTimes = Array(Set(sectionTimes))
        return uniqueSectionTimes.count
    }


    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        var uniqueSectionTimes = Array(Set(sectionTimes))
        let tasksRef = Firebase(url: "\(self.ref)/tasks")
        tasksRef.queryOrderedByChild("dueTime").queryEqualToValue(uniqueSectionTimes[section]).observeEventType(.Value, withBlock: { snapshot in
            var newTasks = [Task]()
            for task in snapshot.children.allObjects as! [FDataSnapshot] {
                let tasks = Task(snapshot: task)
                newTasks.append(tasks)
            }
            self.sectionTasks = newTasks
        })
        return self.sectionTasks.count
    }


    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("TaskCell", forIndexPath: indexPath) as! TaskCell

        // Configure the cell...
        cell.selectionStyle = .None
//        let uniqueSectionTimes = Array(Set(sectionTimes))
//        let times = self.sectionTasks[uniqueSectionTimes[indexPath.section]]
        let task = tasks[indexPath.row]
        cell.label.text = task.title
        ref.childByAppendingPath("tasks").observeEventType(.Value, withBlock: { snapshot in
        if task.done == true {
            cell.checkBox.image = UIImage(named: "checkedbox")
            cell.detailLabel.text = "Completed By: \(task.completedBy)"
            }
            else {
            cell.checkBox.image = UIImage(named: "uncheckedbox")
            cell.detailLabel.text = ""
            }
        })

        cell.delegate = self
        return cell
    }

    override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        let uniqueSectionTimes = Array(Set(sectionTimes))

        return uniqueSectionTimes[section]
    }

我觉得问题的根源可能在 numberOfRowsInSection 和 cellForRowAtIndexPath 中。从 numberOfRowsInSection 中,当我将 self.sectionTasks 设置为等于 newTasks 后打印时,我得到 6 个数组(等于部分的数量),其中包含所有正确的任务正确的数组。但是,当我打印 self.sectionTasks.count 时,我得到了六次“0”,这对我来说没有意义。我不知道要在 cellForRowAtIndexPath 中做什么。我似乎无法在任何地方找到很好的解释它的好教程。

更新 1:

我也在 numberOfRows 中尝试过这个

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        var uniqueSectionTimes = Array(Set(sectionTimes))
        let tasksRef = Firebase(url: "\(self.ref)/tasks")
        tasksRef.queryOrderedByChild("dueTime").queryEqualToValue(uniqueSectionTimes[section]).observeEventType(.Value, withBlock: { snapshot in
            var newTasks = [String]()
            for task in snapshot.children.allObjects as! [FDataSnapshot] {
                let tasks = task.value["title"] as! String
                newTasks.append(tasks)
            }
//            for task in snapshot.children.allObjects as! [FDataSnapshot] {
//                let tasks = Task(snapshot: task)
//                newTasks.append(tasks)
//            }
            self.sectionTasks = newTasks
        })
        print(sectionTasks.count)
        return self.sectionTasks.count
    }

我得到了相同的结果。基本上,这种方式只给我项目的标题,而不是每个数组中的整个项目。但它仍然告诉我所有数组的计数都是 0。

更新 2:

在实现以下代码后,我现在在每个部分下复制了所有任务。我想我需要以某种方式过滤任务,但我不确定在哪里或如何做。

 func queryDueTimes(uniqueSectionTimes:Array<String>) {
        let tasksRef = Firebase(url: "\(self.ref)/tasks")
        tasksRef.queryOrderedByChild("dueTime").observeEventType(.Value, withBlock: { snapshot in
            var newTasks = [Task]()
            for task in snapshot.children.allObjects as! [FDataSnapshot] {
                let times = Task(snapshot: task)
                newTasks.append(times)
            }
            self.sectionTasks = newTasks
            print(self.sectionTasks)
            self.tableView.reloadData()
        })
    }

我在 viewDidLoad() 中运行这个函数,并得到一个大数组,其中包含每个任务的所有元素。我想我需要使用 numberOfRows 中的“section”元素,但我不确定如何使用。此外,我正在查看的教程显示了 cellForRow< 中 indexPath.section 的使用 但我只是不确定如何实现这些东西。

解决方案:

我最终完全更改了查询代码,所以我从本地数组而不是 Firebase 中提取数据。

func querySections() -> [String] {
           var sectionsArray = [String]()
        for task in tasks {
            let dueTimes = task.dueTime
            sectionsArray.append(dueTimes)
        }
        let uniqueSectionsArray = Array(Set(sectionsArray)).sort()
        return uniqueSectionsArray
    }


    func queryDueTimes(section:Int) -> [Task] {
        var sectionItems = [Task]()
        for task in tasks {
            let dueTimes = task.dueTime
            if dueTimes == querySections()[section] {
                sectionItems.append(task)
            }
        }
        return sectionItems
    }



    // MARK: - Table view data source

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return querySections().count
    }



    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return queryDueTimes(section).count
    }


    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("TaskCell", forIndexPath: indexPath) as! TaskCell

        // Configure the cell...
        cell.selectionStyle = .None
        let times = queryDueTimes(indexPath.section)
        let task = times[indexPath.row]
        cell.label.text = task.title
        if task.done == true {
            cell.checkBox.image = UIImage(named: "checkedbox")
            cell.detailLabel.text = "Completed By: \(task.completedBy)"
            }
            else {
            cell.checkBox.image = UIImage(named: "uncheckedbox")
            cell.detailLabel.text = ""
            }

        cell.delegate = self
        return cell
    }

    override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return querySections()[section]
    }

最佳答案

发生这种情况是因为对 taskRef.query... 的调用是异步的。并且 numberOfRowsInSection 方法期望此时您已经知道您拥有的行数。

将查询代码移动到其他方法中,例如

func queryDueTimes(uniqueSectionTimes: Array) { 
    let tasksRef = Firebase(url: "\(self.ref)/tasks")
            tasksRef.queryOrderedByChild("dueTime").queryEqualToValue(uniqueSectionTimes[section]).observeEventType(.Value, withBlock: { snapshot in
                var newTasks = [String]()
                for task in snapshot.children.allObjects as! [FDataSnapshot] {
                    let tasks = task.value["title"] as! String
                    newTasks.append(tasks)
                }
    //            for task in snapshot.children.allObjects as! [FDataSnapshot] {
    //                let tasks = Task(snapshot: task)
    //                newTasks.append(tasks)
    //            }
                self.sectionTasks = newTasks


               //IMPORTANT: reload your table here:
                self.tableView.reloadData()
            })
}

然后,从 View Controller 的 viewDidLoad() 方法调用 queryDueTimes 方法:

func viewDidLoad()
{
    super.viewDidLoad()

    var uniqueSectionTimes = Array(Set(sectionTimes))
    self.queryDueTimes(uniqueSectionTimes)
}

关于ios - 分割 UITableView 单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36068601/

相关文章:

OAuth 2 流程上的 iOS 9 WKWebView didReceiveAuthenticationChallenge

objective-c - 在 objective-c 中扩展协议(protocol)实现

c# - 将 C++ 数组返回到 C#

ios - NSURLSession/NSURLConnection HTTP 加载失败,-9802

macos - 如何禁用 NSTextView 中图像的标记选项?

ios - 如何检测数字是递减还是递增? iOS

ios - 为什么不能将数据写入文件

javascript - React Redux mapStateToProps 在第二次调用中加载数据

java - 给一个arraylist另一个arraylist JAVA的值

Swift 允许协议(protocol)属性和具有不相关类型属性的符合对象之间的名称冲突