2017-01-27 55 views
-4

我有一個ViewController,當我點擊我的保存按鈕時,我有2個TextFields和一個DatePicker視圖我想用我選擇的日期作爲我的TableviewController的部分標題。如果其他對象跟隨,並且他們有相同的日期,他們應該在同一日期組合在一起。我沒有在這個項目中使用CoreData,所以請不要使用CoreData爲這個任務提供的方法。 enter image description hereUITableViewCell分隔符使用日期

+3

請添加一些代碼,突出自己遇到的問題。 – torinpitchers

回答

0

下面是一個簡單的實現,它接受你的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 
    } 
}