ios - NSDateComponents.setValue() 不适用于 iOS 7 及更低版本

标签 ios swift calendar

我需要在当前日期上加一年(swift 和 iOS 7 及更高版本)。但我发现的每个解决方案都只支持 iOS 8 及更高版本。请指导我通过适当的解决方案。 谢谢

 let components: NSDateComponents = NSDateComponents()
    components.setValue(1, forComponent: NSCalendarUnit.Year);
    let date: NSDate = NSDate()
    let expirationDate = NSCalendar.currentCalendar().dateByAddingComponents(components, toDate: date, options: NSCalendarOptions(rawValue: 0))

最佳答案

NSDateComponentssetValue() 方法仅适用于 iOS 8/OS X 10.9 或更高版本:

components.setValue(1, forComponent: NSCalendarUnit.Year)

对于 iOS 7 支持,只需使用

components.year = 1

还要注意

dateByAddingComponents(components, toDate: date, options: NSCalendarOptions(rawValue: 0)

可以写成更短的

dateByAddingComponents(components, toDate: date, options: [])

比较例如Swift 2.0 calendar components error .

关于ios - NSDateComponents.setValue() 不适用于 iOS 7 及更低版本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36278943/

相关文章:

ios - 根据内容自动增加 View 的高度

Swift 4 - 使用结构创建多项选择测验 - 主要缺陷

ios - 滚动时 UITableView 奇怪的布局行为发生变化

json - GSON 将带有日历的对象反序列化为带有 Mongo 日期的 json 并返回

ios - 如何在日历中获取上个月和下个月-Swift

android - 如何为 iOS 和 Android 上的深度链接确定 native 应用程序的参数

android - Flutter:如何将 DropdownButton 菜单图标对齐到最右边?

ios - 为 UIImageView 禁用大型 UIImage

mysql - Grails:我可以让验证器仅适用于创建(而不是更新/编辑)

ios - 在闭包中使用元类型