【问题标题】:How to conditionally section data model in UITableView?如何在 UITableView 中有条件地划分数据模型?
【发布时间】:2018-10-16 06:24:16
【问题描述】:

我有一个从 Firebase 以 JSON 格式返回的模型对象。

{
    "id": 1,
    "name": "Jon Doe",
    "time": ["1525592246"]
},
{
    "id": 2,
    "name": "Jane Doe",
    "time": ["1525592266"]
},

我想根据以下内容将这些对象构造成 UITableView 中的部分:

enum DiarySectionType {
    case Today
    case Tomorrow
    case ThisWeek
    case ThisMonth
    case Later
}

即如果“时间”是今天,它将在 UITableView 的今天部分中

解决此问题的最佳方法是什么?我曾想过为每个单独的数组。但不要认为这是要走的路。

一如既往地感谢任何帮助。

【问题讨论】:

    标签: swift models sections custom-sections


    【解决方案1】:

    首先你需要为你的 Date 提供辅助扩展

    extension Date {
    
        public func component(_ component: Calendar.Component) -> Int {
            let calendar = Calendar.autoupdatingCurrent
            return calendar.component(component, from: self)
        }
    
        public var isToday: Bool {
            let calendar = Calendar.autoupdatingCurrent
            return calendar.isDateInToday(self)
        }
    
        public var isTomorrow: Bool {
            let calendar = Calendar.autoupdatingCurrent
            return calendar.isDateInTomorrow(self)
        }
    
        public var isThisWeek: Bool {
            return isInSameWeek(date: Date())
        }
        public var isThisMonth: Bool {
            return isInSameMonth(date: Date())
        }
        public var islater: Bool {
           return isInSameMonth(date: Date()) ? false : true
        }
    
    }
    extension Date {
        func isInSameWeek(date: Date) -> Bool {
            return Calendar.current.isDate(self, equalTo: date, toGranularity: .weekOfYear)
        }
        func isInSameMonth(date: Date) -> Bool {
            return Calendar.current.isDate(self, equalTo: date, toGranularity: .month)
        }
    }
    

    然后是你的枚举

    enum DiarySectionType:Int{
        case Today
        case Tomorrow
        case ThisWeek
        case ThisMonth
        case Later
        case count // use for number of section
        init (with date:Date){
    
            if date.isToday {
                self = .Today
            }else if date.isTomorrow{
                 self = .Tomorrow
            }else if date.isThisWeek{
                self = .ThisWeek
            }else if date.isThisMonth{
                 self = .ThisMonth
            }else{
               self = .Later
            }
        }
    }
    

    您的数据根据​​需要进行形式化

    struct Item{
        var id : Int
        var name : String
        var time : Double
        init(id:Int, name:String,time:Double) {
    
            self.id = id
            self.name = name
            self.time = time
        }
    }
    

    // 控制器

      class  ViewController: UIViewController{
    
              var data = [Item]() // your data before sections
              var dataWork = [DiarySectionType: [Item]]() // date After sections
    
            override func viewDidLoad() {
                super.viewDidLoad()
    
                self.sortData()
    
              }
    
       // When generating sorted table data we can easily use our TableSection to make look up simple and easy to read.
            func sortData() {
                dataWork[.Today] = data.filter({ DiarySectionType.init(with: Date.init(timeIntervalSince1970: $0.time))  == .Today })
                dataWork[.Tomorrow] = data.filter({ DiarySectionType.init(with: Date.init(timeIntervalSince1970: $0.time))  == .Tomorrow })
                dataWork[.ThisWeek] = data.filter({ DiarySectionType.init(with: Date.init(timeIntervalSince1970: $0.time))  == .ThisWeek })
                dataWork[.ThisMonth] = data.filter({ DiarySectionType.init(with: Date.init(timeIntervalSince1970: $0.time))  == .ThisMonth })
                dataWork[.Later] = data.filter({ DiarySectionType.init(with: Date.init(timeIntervalSince1970: $0.time))  == .Later })
            }
        }
    
    
    
    
    extension ViewController: UITableViewDataSource, UITableViewDelegate {
    
        // As long as `count` is the last case in our TableSection enum,
        // this method will always be dynamically correct no mater how many table sections we add or remove.
        func numberOfSections(in tableView: UITableView) -> Int {
            return DiarySectionType.count.rawValue
        }
    
        func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            // Using Swift's optional lookup we first check if there is a valid section of table.
            // Then we check that for the section there is data that goes with.
            if let tableSection = DiarySectionType(rawValue: section), let data = dataWork[tableSection] {
                return data.count
            }
            return 0
        }
    
        func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
            var title : String = ""
            if let tableSection = DiarySectionType(rawValue: section) {
                switch tableSection {
                case .Today:
                    title = "Today"
                case .Tomorrow:
                    title = "Tomorrow"
                case .ThisMonth:
                    title = "ThisMonth"
                case .ThisWeek:
                    title = "ThisWeek"
                case .Later:
                    title = "Later"
                default:
                    title = ""
                }
            }
    
            return title
        }
    
    
        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
            // Similar to above, first check if there is a valid section of table.
            // Then we check that for the section there is a row.
            if let tableSection = DiarySectionType(rawValue: indexPath.section), let item = dataWork[tableSection]?[indexPath.row] {
              // use item item
    
            }
            return cell
        }
    
    }
    

    【讨论】:

    • 谢谢。可以在客户端/设备上进行所有过滤吗?我将如何实现 numberOfRowsInSection?
    • 无法访问 rawValue
    • 抱歉代码已更新,枚举已更新为 Int 类型 @DavidLintin
    • 关于日期扩展。今天工作正常,但是,测试其他人正在创造违规行为。我正在使用这个网站来计算时间戳。 www.epochconverter.com/ 进入明天/本周时,单元格将显示在表格的后面部分。
    • 好的,让我检查一下,但这是概念。延期很简单,我会帮你查的
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-07
    • 2012-12-09
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多