gpt4 book ai didi

ios - 按日期对 TableView 进行分组和排序

转载 作者:搜寻专家 更新时间:2023-11-01 05:40:22 24 4
gpt4 key购买 nike

我想问一下如何按日期对数据(部分)进行分组?

这是我的代码:

import UIKit
import CoreData

class TableViewController: UITableViewController {

var myList = []

override func viewDidLoad() {
super.viewDidLoad()


}

override func viewDidAppear(animated: Bool) {
let appDel : AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let context : NSManagedObjectContext = appDel.managedObjectContext!

let freq = NSFetchRequest(entityName: "Item")

myList = context.executeFetchRequest(freq, error: nil)!

tableView.reloadData()
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()

}

// MARK: - Table view data source

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {

return 1
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

return myList.count
}


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

var object : NSManagedObject = myList[indexPath.row] as! NSManagedObject

let name = object.valueForKeyPath("name") as! String
let qty = object.valueForKeyPath("qty") as! Int
let date = object.valueForKeyPath("date") as! String

cell.nameLabel.text = name
cell.qtyLabel.text = toString(qty)
cell.dateLabel.text = date

return cell
}

}

详细说明:现在我的日期样本只是一行(默认只有 1 个部分)示例:

apple  1  Jul 10, 2015 (row 1)
orange 7 Jul 10, 2015 (row 2)
grape 5 Jul 11, 2015 (row 3)

我想按日期分组,所以结果如下:

Jul 11, 2015 (section 1)
grape 5 (row 1)
Jul 10, 2015 (section 2)
apple 1 (row 2)
orange 7 (row 3)

注意:部分是动态的,取决于数据和降序排序

谁有解决办法?谢谢

最佳答案

您的列表 myList 应该是字典或数组的形式。

例如,如果它是一个字典,它应该是这样的

var myList: [String: [NSManagedObject]] = [:]

以日期为键

这一切都是为了将​​您的数据分类为正确的格式。在 viewDidAppear 中你可以做类似的事情

for object in freq {
if let array = myList[object.valueForKeyPath("date")!] {
var a = array
a.append(object)
myList[object.date!] = a
} else {
myList[object.date!] = [object]
}
}

然后在 numberOfSectionsInTableView 中,

return myList.count

在 numberOfRowsInSection 中

if let a = myList[sections[section]] {
return a.count
}
return 0
}

已排序的部分

var sections: [String] {
return Array(myList.keys).sorted(<)
}

在cellForRowAtIndexPath中,可以得到一个对应的对象。

let array = myList[sections[indexPath.section]]!
let object = array[indexPath.row]

您还需要使用

实现 viewForHeaderInSection
let date = sections[section]

我确信有更好的方法可以做到这一点,但这足以动态填充表格 View 。我只是想让你看到一个想法。希望对你有帮助。

关于ios - 按日期对 TableView 进行分组和排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31334975/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com