RealmSwift显示每个日期到tableview部分 [英] RealmSwift display for each date to tableview section

查看:106
本文介绍了RealmSwift显示每个日期到tableview部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是swift and realm的新手。

I'm new in swift and realm.

我想显示存储在领域的数据。

I want to display data which are stored in realm.

我想显示每个日期到tableview部分。

I want to display for each date to tableview section.

class Item: Object {
    @objc dynamic var amount: Int = 0
    @objc dynamic var date: Date?
    var parentCategory = LinkingObjects(fromType: Category.self, property: "items")
}



viewController



viewController

import UIKit
import RealmSwift

class HistoryViewController: UITableViewController {

    let realm = try! Realm()
    var items: Results<Item>?

    override func viewDidLoad() {
        super.viewDidLoad()
        items = realm.objects(Item.self)
    }


    override func numberOfSections(in tableView: UITableView) -> Int {
        return items?.count ?? 1
    }

    override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return "represents a day"
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return "Item entries with the corresponding date"
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
        cell.textLabel?.text = amount
        return cell
    }

}



存储日期

date stored

Optional(Results<Item> <0x7ff9ba460610> (
[0] Item {
    amount = 900;
    date = 2018-01-27 06:00:06 +0000;
},
[1] Item {
    amount = 9000;
    date = 2018-01-27 06:20:29 +0000;
},
[2] Item {
    amount = 400;
    date = 2018-01-28 06:22:32 +0000;
},
[3] Item {
    amount = 45;
    date = 2018-01-28 01:21:27 +0000;
},
[4] Item {
    amount = 258665;
    date = 2018-01-30 02:35:45 +0000;
}

))


  • 2018-01-27


    • 900

    • 9000


    • 400

    • 45


    • 258665

    推荐答案

    您必须进行相当多的更改才能根据 date 属性<$ c $的天数对您的tableview进行分组c>项目对应。

    You have to make quite a few changes in order to group your tableview based on days to which the date property of Item corresponds.

    首先,你不应该将所有项目存储为你班级的财产,因为你不会需要一个集合中的所有项目。相反,我建议的方法是使用数组和字典作为表视图的数据源。该数组将存储 Realm <中的条目的唯一日期(数组中的日期对象将对应于特定日期的午夜) / code>。字典将包含与其键相同的日期,值将为结果< Item> ,用于存储每个项目日期属性与特定密钥在同一天。

    First of all, you shouldn't store all items as a property of your class, since you won't be needing all items in one collection. Rather, the approach I suggest is to use an Array and a Dictionary as the data sources for your table view. The array will store the unique days (the Date objects in the array will correspond to midnight of the specific day) for which you have entries in Realm. The dictionary will contain the same days as its keys and the values will be of type Results<Item> for storing each Item whose date property is on the same day as the specific key.

    我在操场上测试了以下代码它按预期工作。

    I have tested below code in a playground and its working as expected.

    class HistoryViewController: UITableViewController {
    
        let realm = try! Realm()
        var groupedItems = [Date:Results<Item>]()
        var itemDates = [Date]()
    
        override func viewDidLoad() {
            super.viewDidLoad()
            let items = realm.objects(Item.self)
            //Find each unique day for which an Item exists in your Realm
            itemDates = items.reduce(into: [Date](), { results, currentItem in
                let date = currentItem.date!
                let beginningOfDay = Calendar.current.date(from: DateComponents(year: Calendar.current.component(.year, from: date), month: Calendar.current.component(.month, from: date), day: Calendar.current.component(.day, from: date), hour: 0, minute: 0, second: 0))!
                let endOfDay = Calendar.current.date(from: DateComponents(year: Calendar.current.component(.year, from: date), month: Calendar.current.component(.month, from: date), day: Calendar.current.component(.day, from: date), hour: 23, minute: 59, second: 59))!
                //Only add the date if it doesn't exist in the array yet
                if !results.contains(where: { addedDate->Bool in
                    return addedDate >= beginningOfDay && addedDate <= endOfDay
                }) {
                    results.append(beginningOfDay)
                }
            })
            //Filter each Item in realm based on their date property and assign the results to the dictionary
            groupedItems = itemDates.reduce(into: [Date:Results<Item>](), { results, date in
                let beginningOfDay = Calendar.current.date(from: DateComponents(year: Calendar.current.component(.year, from: date), month: Calendar.current.component(.month, from: date), day: Calendar.current.component(.day, from: date), hour: 0, minute: 0, second: 0))!
                let endOfDay = Calendar.current.date(from: DateComponents(year: Calendar.current.component(.year, from: date), month: Calendar.current.component(.month, from: date), day: Calendar.current.component(.day, from: date), hour: 23, minute: 59, second: 59))!
                results[beginningOfDay] = realm.objects(Item.self).filter("date >= %@ AND date <= %@", beginningOfDay, endOfDay)
            })
        }
    
    
        override func numberOfSections(in tableView: UITableView) -> Int {
            return itemDates.count
        }
    
        override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
            return "represents a day"
        }
    
        override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return groupedItems[itemDates[section]]!.count
        }
    
        override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
            let itemsForDate = groupedItems[itemDates[indexPath.section]]!
            cell.textLabel?.text = "\(Array(itemsForDate.sorted(byKeyPath: "date"))[indexPath.row].amount)"
            return cell
        }
    
    }
    

    这篇关于RealmSwift显示每个日期到tableview部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆