RealmSwift显示每个日期到tableview部分

时间:2018-02-05 11:02:46

标签: ios swift uitableview realm

我是swift and realm的新人。

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

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

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

的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
    }

}
存储日期
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年1月27日
    • 900
    • 9000
  • 2018年1月28日
    • 400
    • 45
  • 2018年1月30日
    • 258665

1 个答案:

答案 0 :(得分:3)

您必须进行相当多的更改才能根据date Item属性对应的天数对您的tableview进行分组。

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

我在游乐场测试了下面的代码,并按预期工作。

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
    }

}