Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Sorting a UITableView by a NSDate object with headers in Swift
extension NSDate{
convenience
init(inputDate: NSDate){
let calendar = NSCalendar.currentCalendar()
let timeZone = NSTimeZone.systemTimeZone()
calendar.timeZone = timeZone
let comps = calendar.components([NSCalendarUnit.Year, NSCalendarUnit.Month, NSCalendarUnit.Day ], fromDate: inputDate)
comps.hour = 0
comps.minute = 0
comps.second = 0
let returnDate = calendar.dateFromComponents(comps)
self.init(timeInterval:0, sinceDate:returnDate!)
}
}
class SortedTableView: UITableViewController {
var sortedArray: Array<AnyObject>?
var sections: NSMutableDictionary?
var mealArray: NSMutableArray?
override func viewDidLoad() {
super.viewDidLoad()
mealArray = NSMutableArray()
mealArray?.addObject(["meal": "banana", "date": NSDate()])
for object in mealArray! {
let dict = object as! NSMutableDictionary
if let exists = dict["date"] {
let date = NSDate(inputDate: exists as! NSDate)
var eventsOnThisDay = sections?.objectForKey(date)
if eventsOnThisDay == nil {
eventsOnThisDay = NSMutableArray()
sections?.setObject(eventsOnThisDay!, forKey: date)
}
eventsOnThisDay!.addObject(dict)
let unsorted = sections?.allKeys
self.sortedArray = unsorted!.sort({ $0.date.compare($1.date) == .OrderedAscending })
} else {
}
}
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
if mealArray?.count == 0 || mealArray == nil {
let label = UILabel.init(frame: self.view.frame)
label.textColor = UIColor.whiteColor()
label.text = "No meals"
label.tag = 6
self.tableView.separatorStyle = .None
label.textAlignment = .Center
self.tableView.backgroundView = label
return (self.sections?.count)!
}
self.tableView.separatorStyle = .SingleLine
self.tableView.backgroundView = nil
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if(mealArray == nil){
return 0
}else{
let date = self.sortedArray![section] as! NSDate
let events = self.sections?.objectForKey(date)
return (events?.count)!
}
}
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
let formatter = NSDateFormatter.init()
formatter.timeStyle = .NoStyle
formatter.dateStyle = .MediumStyle
return formatter.stringFromDate(self.sortedArray![section] as! NSDate)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.