0

我有一个表格单元格视图,目前有一个日期和标题。但我也想添加当前时间,但我似乎无法在单元格中添加另一个部分。有人可以告诉我怎么做吗?

这是我的 cellForRowAt:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "ContactCell", for: indexPath)

    let contact = userInput[indexPath.row]

    cell.detailTextLabel?.numberOfLines = 3
    cell.detailTextLabel?.text = contact.value(forKey:"thf") as? String
    cell.textLabel?.text = contact.value(forKey:"date") as? String

    return cell
}

我不介意在任何地方添加时间,但最好是在明显的地方

这是它的样子

4

1 回答 1

0
  1. 首先将以下代码写入您的日期扩展

    extension Date {
        func getFormattedDate(format: String) -> String {
            let dateFormatter = DateFormatter()
            dateFormatter.dateFormat = format
            let strDate = dateFormatter.string(from: self)
            return strDate
        }
    
        func getTimeStamp() -> String {
            let dateFormatter = DateFormatter()
            dateFormatter.dateFormat = "hh:mm a"
            let dateString = dateFormatter.string(from: self)
            return dateString
        }
    }
    
  2. 现在使用我在下面使用的日期方法:

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "ContactCell", for: indexPath)
        let contact = userInput[indexPath.row]
        cell.yourDateLabel?.text = (contact.value(forKey:"keyforDate") as? Date).getFormattedDate(format: "MMM dd,yyyy")
        cell.yourTimeLabel?.text = (contact.value(forKey:"keyforDate") as? Date).getTimeStamp()
        return cell    
    }
    
于 2018-11-01T03:52:41.023 回答