ios - 从字典获取字符串到 NSDate

标签 ios swift uitableview

我的 swift 文件有这个代码

数据.swift

class Data {
    class Entry {
        let filename: String
        let heading: String
        let dates: String
        init(fname: String, heading: String, dates: String) {
            self.heading = heading
            self.filename = fname
            self.dates = dates
        }
    }
    let places = [
        Entry(fname: "bridge.jpeg", heading: "Heading 1", dates: "26/04/2016"),
        Entry(fname: "mountain.jpeg", heading: "Heading 2", dates: "26/04/2016"),
        Entry(fname: "snow.jpeg", heading: "Heading 3", dates: "26/04/2016"),
        Entry(fname: "sunset.jpeg", heading: "Heading 4", dates: "26/04/2016")
    ]
}

我设法像这样在 TableView 上访问它

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as PlacesTableViewCell

    let entry = data.places[indexPath.row]
    let image = UIImage(named: entry.filename)
    cell.bkImageView.image = image
    cell.headingLabel.text = entry.heading
    cell.dateLabel.text = entry.dates
    return cell
}

但是在另一个文件“ViewController”中的 TableView 之外,我不知道如何访问它“日期”并将其转换为 NSDate?!

最佳答案

这是一个很棒的 NSDate 扩展,它允许您将日期保存为 NSDate。您需要将“日期”属性更改为 NSDate。

将以下代码粘贴到它自己的文件中或任何类之外,然后每当您编写 NSDate( 时,它都会允许您输入字符串,只需确保格式为 yyyy-mm-dd

extension NSDate {
  convenience
  init(dateString:String) {
let dateStringFormatter = NSDateFormatter()
dateStringFormatter.dateFormat = "yyyy-MM-dd"
dateStringFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
let d = dateStringFormatter.dateFromString(dateString)!
self.init(timeInterval:0, sinceDate:d)
  }
}

如果我能找到原始帖子,我会链接到它。

关于从其他 Controller 访问日期,您可以使用此处的答案:

Swift nested class properties

我实际上建议将 Entry 类放在自己的文件中,并将地方数组放入结构中,这使得可以从项目中的任何位置轻松访问它:

class Entry {
let filename: String
let heading: String
let dates: String

init(fname: String, heading: String, dates: String) {

  self.heading = heading
  self.filename = fname
  self.dates = dates
  }
 }

struct Data {

static let places = [
 Entry(fname: "bridge.jpeg", heading: "Heading 1", dates: "26/04/2016")]
}

然后使用以下命令进行访问:

let data = Data()
let entry = data.places[0].dates

关于ios - 从字典获取字符串到 NSDate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35587330/

相关文章:

ios - 是否可以在选项卡栏项 (BadgeValue) 中添加 UILabel

ios - 核心数据 MOC 保存暂停执行且保存失败(无错误或崩溃)

ios - 按下按钮时更改行的颜色 - 快速

ios - 在 UITableViewCell 上重新渲染 subview 的最佳实践

iphone - 我如何使一个表格 View 指向具有另一个表格 View 的页面?

ios - 来 self 的自定义键盘的 Apple 表情符号键盘

ios - 你如何将数据从 Objective C 传递到 Swift?

swift - 我的 View Controller 不符合 GMSFetcherAutocompleteDelegate 协议(protocol)

ios - UITableViewCell 高度变化时闪烁

ios - Swift - 如何识别哪个自定义 tableview 单元格已被修改?