Swift 5- Firebase-标题中按日期分组

如何解决Swift 5- Firebase-标题中按日期分组

我的主要目标是从Firebase数据库中获取日期,并将其用作部分标题,以便我可以在该标题下加载所有具有相同日期的事件。

我希望它像这样显示在我的表格视图中:

9月-标头

-2020年9月29日-sub标头

-事件

-事件

-事件

-2020年9月30日-sub标头

-事件

-事件

-事件

这是我的主要View Controller。

import UIKit
    import Foundation
    import Firebase
    import FirebaseDatabase

    class EventsTableViewController: UIViewController {
        var sectionNames: [String] = []
        var events: [String: [EventsInfo]] = [:]
        var datref: DatabaseReference!
        var eventView = [EventsInfo]()

        @IBOutlet weak var eventTableView: UITableView!

        override func viewDidLoad() {
            super.viewDidLoad()
            getEventsFromFirebaseDB()
        }
        
        
        deinit {
               datref.removeAllObservers()
           }
           
           private func eventsFetched(_ eventData: [EventsInfo])
           {
               for event in eventData
               {
                guard let eventNameFirstChar = event.date.first else { continue }
                
                   if var eventsForKey = events["\(eventNameFirstChar)"]
                   {
                       eventsForKey.append(event)
                       events["\(eventNameFirstChar)"] = eventsForKey
                   }
                   else
                   {
                       // no users are stored in dictionary for key userNameFirstChar
                       events["\(eventNameFirstChar)"] = [event]
                   }
               }
           
               // sort dictionary keys and set it in sectionNames
               sectionNames = events.map { $0.key }.sorted()
            
            print (sectionNames)
           }
           
        private func getEventsFromFirebaseDB() {
               datref = Database.database().reference().child("events")
                datref.observe(DataEventType.value,with: { [weak self] (snapshot) in
               
                       guard snapshot.childrenCount > 0 else { return }
               
                       var events: [EventsInfo] = []
                       for event in snapshot.children.allObjects as! [DataSnapshot]
                       {
                           let object = event.value as? [String: AnyObject]
               
                           let title = object?["title"]
                           let place = object?["place"]
                           let info = object?["info"]
                           let date = object?["date"]
                           let time = object?["time"]
               
                        let event = EventsInfo(title: title as! String,place: place as! String,info: info as! String,time: time as! String,date: date  as! String)
                           events.append(event)
                            }

                    self?.eventsFetched(events)
                    self?.eventTableView.reloadData()
                        })
            }

        override func prepare(for segue: UIStoryboardSegue,sender: Any?) {
            if segue.identifier == "showEvent"
            {
                if let indexPath = eventTableView.indexPathForSelectedRow
                {
                    let destinationController = segue.destination as! EventsInfoViewController
                    let char = sectionNames[indexPath.section]
                    let event = events[char]![indexPath.row]
                    destinationController.EventsData = event
                }
            }
        }

    }


    extension EventsTableViewController: UITableViewDataSource,UITableViewDelegate {
        
        func numberOfSections(in tableView: UITableView) -> Int {
            sectionNames.count
        }

        func tableView(_ tableView: UITableView,titleForHeaderInSection section: Int) -> String? {
              sectionNames[section]
          }


        func tableView(_ tableView: UITableView,numberOfRowsInSection section: Int) -> Int {
            let char = sectionNames[section]
               return events[char]!.count
            }

        func tableView(_ tableView: UITableView,cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
            let cell = eventTableView.dequeueReusableCell(withIdentifier: "eventsCell") as! EventsTableViewCell
            let char = sectionNames[indexPath.section]
            let event = events[char]![indexPath.row]
            cell.eventTitleLabel.text = event.title
            return cell
        }


    func tableView(_ tableView: UITableView,didSelectRowAt indexPath: IndexPath) {
            performSegue(withIdentifier: "showEvent",sender: self)
    }

这是我的EventsInfo文件


import Foundation


class EventsInfo {
    
    var title: String
    var place: String
    var info: String
    var time: String
    var date: String
    
    
    init(title: String,place: String,info: String,time: String,date: String) {
        
        self.title = title
        self.place = place
        self.info = info
        self.time = time
        self.date = date

    }
}

This is what i current have but am looking to load the date into the section header instead

This is my Firebase file that I have my Date in for the TableView.

解决方法

我正在给出一个答案,希望它可以通过一个例子提供一些指导。请注意,这与Firebase无关-纯粹是tableView管理。

我们的应用程序列出了一些水果,其中标题标题是每个水果的名字

A
   Apple
B
   Banana

这是一个用于保存每个部分的数据的结构,然后是一个用于保存这些对象的类数组(tableView dataSource)

struct FruitStruct {
   var sectionTitle = ""
   var fruitNameArray = [String]()
}

var fruitDataSource = [FruitStruct]()

然后让我们填充数据

func setupDataSourceData() {
    let fruitArray = ["Apple","Pear","Banana","Bing Cherry","Grape","Orange","Plum","Watermelon","Cantelope"]

    let allFirstChars = fruitArray.map { String($0.prefix(1)) } //get all first chars for section titles
    let sectionTitles = Array(Set(allFirstChars)).sorted() //eliminate dups and sort

    //iterate over the unique section titles and get the fruits that are in that section
    // sort and then craft structs to hold the title and the associated fruits
    sectionTitles.forEach { firstChar in
        let results = fruitArray.filter { $0.prefix(1) == firstChar }
        let sortedFruits = results.sorted()
        let fruit = FruitStruct(sectionTitle: firstChar,fruitNameArray: sortedFruits)
        fruitDataSource.append(fruit)
    }

    //this code is to just output the data to console so you can see what it
    //  looks like. Remove it.
    for fruitData in fruitDataSource {
        print(fruitData.sectionTitle)
        let fruits = fruitData.fruitNameArray
        for fruitName in fruits {
            print("  \(fruitName)")
        }
    }
}

最后,使用tableView委托方法从dataSource填充tableView

//
//handle sections
//
func numberOfSections(in tableView: UITableView) -> Int {
    return self.fruitDataSource.count
}

func tableView(_ tableView: UITableView,titleForHeaderInSection section: Int) -> String? {
    let title = self.fruitDataSource[section].sectionTitle
    return title
}

//
//handleTableView rows
//
func tableView(_ tableView: UITableView,numberOfRowsInSection section: Int) -> Int {
    let rowsInSection = self.fruitDataSource[section].fruitNameArray.count
    return rowsInSection
}

func tableView(_ tableView: UITableView,cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cellReuseIdentifier",for: indexPath)
    let text = self.fruitDataSource[indexPath.section].fruitNameArray[indexPath.row]
    cell.textLabel?.text = text
    return cell
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams['font.sans-serif'] = ['SimHei'] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -> systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping("/hires") public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate<String
使用vite构建项目报错 C:\Users\ychen\work>npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)> insert overwrite table dwd_trade_cart_add_inc > select data.id, > data.user_id, > data.course_id, > date_format(
错误1 hive (edu)> insert into huanhuan values(1,'haoge'); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive> show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 <configuration> <property> <name>yarn.nodemanager.res