【问题标题】:UITableViewCell Separator using a date使用日期的 UITableViewCell 分隔符
【发布时间】:2017-06-13 06:10:42
【问题描述】:

我有一个 ViewController,其中有 2 个 TextField 和一个 DatePicker 视图,当我单击“保存”按钮时,我想使用我选择的日期作为 TableviewController 的部分标题。如果其他对象紧随其后并且它们具有相同的日期,则它们应全部组合在同一日期部分中。我在这个项目中没有使用CoreData,所以请不要建议使用CoreData为此任务提供的方法。enter image description here

【问题讨论】:

  • 请添加一些代码,突出您遇到的问题。

标签: swift uitableview date separator


【解决方案1】:

这是一个简单的实现,它使用您的 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
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-05
    • 2014-01-19
    • 1970-01-01
    • 2022-01-01
    • 1970-01-01
    • 2020-09-06
    相关资源
    最近更新 更多