trever trever - 9 months ago 28
iOS Question

UITableView Section Titles

I am attempting to create a UITableView with sections from my Parse objects. I have the Parse objects successfully. However, I am not sure how or what the best way to get the dates out of the objects to create my sections titles would be.

If I have an array of the objects should I just for through and create a date list? How would I relate that back to the date and that the object should be under that date

I was thinking of using a struct with Date and Item vars to hold the data cleaner, but I don't know I can do it that way either

Any suggestions / examples of what is the best way to do this?

EDIT:

func getExpenses() {
let query = ExpenseItem.query()
query?.order(byDescending: "expenseDate")
query?.findObjectsInBackground(block: { (expenseResult, error) in
if error == nil {

var sectionArray = [ExpenseItem]()

for object in expenseResult as! [ExpenseItem] {
if let firstObject = sectionArray.first {
if Calendar.current.compare(firstObject.expenseDate, to: object.expenseDate, toGranularity: .day) != .orderedSame {
self.tableData.append(sectionArray)
sectionArray = [ExpenseItem]()
}
} else {
sectionArray.append(object)
}
}

if sectionArray.count != 0 {
self.tableData.append(sectionArray)
}
}
})
}

Answer Source
  1. Sort your array data from Parse into ascending order by date.
  2. Declare an array of arrays of PFObject (or your PFObject subclass if you have one): var tableData: [[PFObject]]()
  3. Loop through your Parse data, splitting it by date:

var sectionArray = [PFObject]()
// pfObjects contains the objects you retrieved from Parse, ordered by date
for object in pfObjects {
   if let firstObject = sectionArray.first {
       if object["dateField"] != firstObject["dateField"] {
           self.tableData.append(sectionArray)
           sectionArray = [PFObject]()
       }
   }
   sectionArray.append(object)
}
if sectionArray.count != 0 {
    self.tableData.append(sectionArray)
}
  1. Now you have the data structure you need. The number of sections is the count of the outer array and the number of items in each section is the number of items in each inner array:

 override func numberOfSections(in tableView: UITableView) -> Int {
     return self.tableData.count
 }

  override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
      return self.tableData[section].count
  }

  override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
      let item = self.tableData[indexPath.section][indexPath.row]

      // deque a cell and configure it with item

  }

To get the section header for each section, you can just use the date of the first object in that section's array, since all objects in the section have the same date.