如何按日期升序快速排序Tableview行 [英] How to SORT Tableview rows according to Date Ascending order in swift
问题描述
我有eventsTableView ..无论日期是什么,这里所有行都一一加..但是这里我需要根据它的日期显示tableview orderedAscending
I have eventsTableView.. here all row are adding one by one no matter what the date is.. but here i need to display tableview according to its date orderedAscending
,总代码为:
class EventsViewController: UIViewController {
var eventList : EventsModel? = nil
@IBOutlet weak var eventsTableView: UITableView!
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
getAllEventsList()
}
func getAllEventsList() {
//URLs and code..
do {
let jsonObject = try JSONSerialization.jsonObject(with: data!, options: .mutableLeaves) as! [String :AnyObject]
print("publish event \(jsonObject)")
self.eventList = EventsModel.init(fromDictionary: jsonObject)
DispatchQueue.main.async {
if self.eventList?.events.count != 0 {
DispatchQueue.main.async {
self.eventsTableView.reloadData()
}
}
else {
DispatchQueue.main.async {
Constants.showAlertView(alertViewTitle: "", Message: "No Events \(self.eventType)", on: self)
self.eventList?.events.removeAll()
self.eventsTableView.reloadData()
}
}
dataTask.resume()
}
}
extension EventsViewController : UITableViewDelegate,UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return eventList?.events.count ?? 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: EventsTableViewCell = tableView.dequeueReusableCell(withIdentifier: "EventsTableViewCell") as! EventsTableViewCell
let event = eventList!.events[indexPath.row]
if event.isAllDayEvent == true{
cell.eventDate.text = event.eventDate
cell.nameLbl.text = event.eventName
}
else{
cell.cancelLbl.text = ""
cell.nameLbl.text = event.eventName
cell.eventDate.text = event.eventDate
return cell
}
}
这是EventsModel代码: 就像我们创建的模型一样..如何从此处对日期进行排序
class EventsModel : NSObject, NSCoding {
var events : [EventsModelEvent]!
init(fromDictionary dictionary: [String:Any]){
events = [EventsModelEvent]()
if let eventsArray = dictionary["Events"] as? [[String:Any]]{
for dic in eventsArray{
let value = EventsModelEvent(fromDictionary: dic)
events.append(value)
}
}
}
func toDictionary() -> [String:Any]
{
var dictionary = [String:Any]()
if events != nil{
var dictionaryElements = [[String:Any]]()
for eventsElement in events {
dictionaryElements.append(eventsElement.toDictionary())
}
dictionary["events"] = dictionaryElements
}
return dictionary
}
这是EventsModelEvent
class EventsModelEvent : NSObject, NSCoding {
var eventName : String!
var eventDate: string!
init(fromDictionary dictionary: [String:Any]){
eventName = dictionary["eventName"] as? String
eventDate = dictionary["eventDate"] as? String
}
}
请帮助我以日期升序显示tableview行.
please help me to display tableview row with date ascending order.
推荐答案
此处是一种可用于按日期对事件进行排序的方法.我已经采用了很多代码,只是专注于如何对自定义类型(如 Event
)进行排序.您应该做的第一件事就是遵守 EventsModelEvent
类中的 Comparable
协议,如下所示(我对 CustomStringConvertible
的遵循只是为了打印出结果):
Here is a method that you could use to sort your events by date. I've taken a lot of the code that you have out to just focus on how you would go about sorting a custom type like Event
. The first thing you should do is conform to the Comparable
protocol in your EventsModelEvent
class like below (my conformance to CustomStringConvertible
is just to print out the results):
class Event: Comparable, CustomStringConvertible {
它将引发错误,并说此类不符合Comparable且此类不符合Equatable,是否要添加协议存根?单击是",它将在类中添加小于(<)和等于(==)运算符作为静态方法.因为您说过要它们按升序排序,所以您还需要添加大于(>).
It will throw an error and say that this class does not conform to Comparable and this class does not conform to Equatable, would you like to add protocol stubs? Click yes, and it will add the less than (<) and equal to (==) operators as static methods in the class. Since you said that you want them sorted in ascending order you will also need to add greater than (>).
static func < (lhs: Test, rhs: Test) -> Bool {
(code)
}
static func == (lhs: Test, rhs: Test) -> Bool {
(code)
}
static func > (lhs: Event, rhs: Event) -> Bool {
(code)
}
您当前的日期类型为 String
,在对日期进行排序时将不起作用.要解决此问题,请在您的 EventsModelEvent
类中添加一个方法,以格式化日期,如下所示.实现此方法的方式将根据日期在字符串中的显示方式而有所不同,但这是一个示例:
You currently have date being of type String
which won't work when sorting dates. To get around this, add a method to your EventsModelEvent
class to format the date like below. The way you implement this will vary based on how the date is shown in your string, but here is one example:
private func formatDate() -> Date? {
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .medium //Format is Aug 26, 2020
return dateFormatter.date(from: self.date)
}
这将在您正确指定日期格式的情况下,从date属性中创建一个可选日期.现在,您说您希望比较基于日期的事件,特别是按升序排序的事件.在比较方法中,您希望返回左侧日期(las)和右侧日期(res)的比较,如下所示.
This will create an optional date from your date property, assuming that you have correctly specified the date format. Now, you said that you wish to compare events based on date, specifically sorted in ascending order. Inside of your comparison methods, you want to return the comparison of the date on the left hand side (las) and the date on the right hand side (res) like below.
static func < (lhs: Event, rhs: Event) -> Bool {
return lhs.formatDate()! < rhs.formatDate()!
}
static func > (lhs: Event, rhs: Event) -> Bool {
return lhs.formatDate()! > rhs.formatDate()!
}
static func == (lhs: Event, rhs: Event) -> Bool {
return lhs.name == rhs.name
}
请注意,在此示例中我强制解包,因此如果 formatDate()
返回的日期为零,则程序将崩溃.现在,您要将方法添加到 EventsModel
中,以按日期升序对Array进行排序,并且可以使用 sorted(by:)
方法进行此操作.这是按以下方式实现的.
Note that I force unwrapped in this example, so the program would crash if the date returned by formatDate()
was nil. Now you want to add the method to your EventsModel
to sort the Array by date in ascending order and can use the sorted(by:)
method to do so. This is implemented as below.
func sortByDate() -> [Event] {
return events.sorted(by: >)
}
现在,如果我创建如下所示的 Event
数组,则可以对其进行排序.
Now if I create an array of Event
like below I can sort it.
let events = Events(events: [Event(name: "one", date: "Jan 1, 1993"), Event(name: "two", date: "Dec 31, 2016"), Event(name: "three", date: "Aug 16, 2020")])
print(events)
印刷品[1993年1月1日,两次,2016年12月31日,2020年8月16日,三]
prints [one, Jan 1, 1993, two, Dec 31, 2016, three, Aug 16, 2020]
let sortedEvents = events.sortByDate()
print(sortedEvents)
印刷品[2020年8月16日,三,2016年12月31日,两次,1993年1月1日,一]
prints [three, Aug 16, 2020, two, Dec 31, 2016, one, Jan 1, 1993]
或更简洁地说:
let eventsSorted = Events(events: [Event(name: "one", date: "Jan 1, 1993"), Event(name: "two", date: "Dec 31, 2016"), Event(name: "three", date: "Aug 16, 2020")]).sortByDate()
print(eventsSorted)
印刷品[2020年8月16日,三,2016年12月31日,两个,1993年1月1日,一个]
Prints [three, Aug 16, 2020, two, Dec 31, 2016, one, Jan 1, 1993]
所有课程:
class Events: CustomStringConvertible {
var events: [Event]
var description: String {
return events.description
}
func sortByDate() -> [Event] {
return events.sorted(by: >)
}
init(events: [Event]) {
self.events = events
}
}
class Event: Comparable, CustomStringConvertible {
var description: String {
return "\(name), \(date)"
}
var name: String
var date: String
private func formatDate() -> Date? {
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .medium
return dateFormatter.date(from: self.date)
}
static func < (lhs: Event, rhs: Event) -> Bool {
return lhs.formatDate()! < rhs.formatDate()!
}
static func > (lhs: Event, rhs: Event) -> Bool {
return lhs.formatDate()! > rhs.formatDate()!
}
static func == (lhs: Event, rhs: Event) -> Bool {
return lhs.name == rhs.name
}
init(name: String, date: String) {
self.name = name
self.date = date
}
}
这篇关于如何按日期升序快速排序Tableview行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!