I have a ViewController in which I have 2 TextFields and one DatePicker view when I click my Save Button I want to use the date I picked to be the section Header of my TableviewController. If other Objects follow and they have the same date they should all group together in the same date Section. I'm not using CoreData in this project so please don't propose using the method that CoreData Provides for this Task.enter image description here
Here's a simple implementation, which takes your tableData, and maintains a list of unique dates to be used as section headers. In this example, I recreate the headers from scratch , but in a real implementation, you may want to update instead.
I defined a struct for my sample data
struct SampleData
{
var date = Date()
var textField1 = ""
var textField2 = ""
}
and created some data
var tableData : [SampleData] = []
var tableDataSectionHeaderData : [Date] = []
override func viewDidLoad()
{
super.viewDidLoad()
tableData.append(SampleData(date: stringAsDate("Feb 13, 2017")!, textField1: "Title 1", textField2: "text2"))
tableData.append(SampleData(date: stringAsDate("Feb 13, 2017")!, textField1: "Title 2", textField2: "text2"))
tableData.append(SampleData(date: stringAsDate("Feb 14, 2017")!, textField1: "Title 3", textField2: "text2"))
// and so on...
createSectionHeaders()
}
func createSectionHeaders()
{
tableDataSectionHeaderData.removeAll() // in a realistic scenario, you would probably update this rather than recreating from scratch
for entry in tableData
{
if !tableDataSectionHeaderData.contains(entry.date)
{
tableDataSectionHeaderData.append(entry.date)
}
}
}
I have a couple of functions defined to switch between Date and String.
here's how to implement the tableView methods
extension ViewController : UITableViewDelegate, UITableViewDataSource
{
func numberOfSections(in tableView: UITableView) -> Int
{
return tableDataSectionHeaderData.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
let filteredData = tableData.filter{$0.date == tableDataSectionHeaderData[section]}
return filteredData.count
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String?
{
return dateAsString(tableDataSectionHeaderData[section])
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
let filteredData = tableData.filter{$0.date == tableDataSectionHeaderData[indexPath.section]}
cell.textLabel?.text = "\(dateAsString(filteredData[indexPath.row].date)) \(filteredData[indexPath.row].textField1)"
return cell
}
}