如何获取注释放置的时间 iOS
How To Get How Long Ago An Annotation Was Placed iOS
所以我正在使用 iOS Mapkit
,应用程序的一部分要求我在很久以前显示当有人点击它时放置的注释。到目前为止我试过这个:
//MARK: Report Date And Time Details
let ReportTime = NSDate()
let TimeStamp = NSDateFormatter()
TimeStamp.timeStyle = NSDateFormatterStyle.ShortStyle
TimeStamp.dateStyle = NSDateFormatterStyle.ShortStyle
TimeStamp.stringFromDate(ReportTime)
然后将注释的描述设置为Report Time
。我不想这样做,而是希望注释说“53、54、55 分钟前等”。有没有简单的方法可以做到这一点?
谢谢大家!
两件事:
为了得到经过的时间,我建议使用 NSDateComponentsFormatter
:
let formatter = NSDateComponentsFormatter()
formatter.allowedUnits = [.Hour, .Minute]
formatter.unitsStyle = .Full
let string = formatter.stringFromDate(date1, toDate: date2)
生成的字符串如下所示:
2 hours, 1 minute
如果您只想让标注显示经过的时间,最简单的方法是为 title
(或 subtitle
,随你喜欢)。例如:
class CustomAnnotation: NSObject, MKAnnotation {
let startDate = NSDate()
var coordinate: CLLocationCoordinate2D
var subtitle: String?
init(coordinate: CLLocationCoordinate2D) {
self.coordinate = coordinate
super.init()
}
var title: String? {
let formatter = NSDateComponentsFormatter()
formatter.allowedUnits = [.Hour, .Minute]
formatter.unitsStyle = .Full
let elapsedString = formatter.stringFromDate(startDate, toDate: NSDate())!
return "Added \(elapsedString) ago"
}
}
请注意,这里的关键是我使用的是计算的 属性,而不是使用 MKPointAnnotation
获得的 title
的存储 属性。这确保每次显示标注时,它都会重新检索 属性,并且 NSDateComponentsFormatter
将重新计算经过时间的适当字符串表示形式。
显然,您可以根据需要更改它(例如 startDate
真的只是在您创建注释时,或者它是一些存储的 属性 可以从您的数据源中设置;您可以更改初始化程序以传递其他属性;等等),但这说明了基本思想。
所以我正在使用 iOS Mapkit
,应用程序的一部分要求我在很久以前显示当有人点击它时放置的注释。到目前为止我试过这个:
//MARK: Report Date And Time Details
let ReportTime = NSDate()
let TimeStamp = NSDateFormatter()
TimeStamp.timeStyle = NSDateFormatterStyle.ShortStyle
TimeStamp.dateStyle = NSDateFormatterStyle.ShortStyle
TimeStamp.stringFromDate(ReportTime)
然后将注释的描述设置为Report Time
。我不想这样做,而是希望注释说“53、54、55 分钟前等”。有没有简单的方法可以做到这一点?
谢谢大家!
两件事:
为了得到经过的时间,我建议使用
NSDateComponentsFormatter
:let formatter = NSDateComponentsFormatter() formatter.allowedUnits = [.Hour, .Minute] formatter.unitsStyle = .Full let string = formatter.stringFromDate(date1, toDate: date2)
生成的字符串如下所示:
2 hours, 1 minute
如果您只想让标注显示经过的时间,最简单的方法是为
title
(或subtitle
,随你喜欢)。例如:class CustomAnnotation: NSObject, MKAnnotation { let startDate = NSDate() var coordinate: CLLocationCoordinate2D var subtitle: String? init(coordinate: CLLocationCoordinate2D) { self.coordinate = coordinate super.init() } var title: String? { let formatter = NSDateComponentsFormatter() formatter.allowedUnits = [.Hour, .Minute] formatter.unitsStyle = .Full let elapsedString = formatter.stringFromDate(startDate, toDate: NSDate())! return "Added \(elapsedString) ago" } }
请注意,这里的关键是我使用的是计算的 属性,而不是使用
MKPointAnnotation
获得的title
的存储 属性。这确保每次显示标注时,它都会重新检索 属性,并且NSDateComponentsFormatter
将重新计算经过时间的适当字符串表示形式。
显然,您可以根据需要更改它(例如 startDate
真的只是在您创建注释时,或者它是一些存储的 属性 可以从您的数据源中设置;您可以更改初始化程序以传递其他属性;等等),但这说明了基本思想。