这是一个简单的实现,它使用您的 tableData,并维护一个唯一日期列表以用作部分标题。在此示例中,我从头开始重新创建标头,但在实际实现中,您可能需要更新。
我为我的示例数据定义了一个结构
struct SampleData
{
var date = Date()
var textField1 = ""
var textField2 = ""
}
并创建了一些数据
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)
}
}
}
我定义了几个函数来在日期和字符串之间切换。
这里是如何实现 tableView 方法
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
}
}