Goord Morning一起来,
我有一个带有ios 8和swift的应用程序。
在UIViewcontroller
UIDatepicker
我设定了最短日期。例如今天的日期:2 |五月| 2015年 使用此解决方案,不应该设置过去的日期
但是如果想将此日期设置为15 |一月| 2016
我在第一天开始设置为15
比1月到1月,但UIDatepicker
回到2015年5月2日的最短日期
是否有可能,将当天改为15,将月份改为1月,那一年会自动变为2016年?
答案 0 :(得分:3)
让你的minimumDate取消设置并尝试按代码配置...
试试这个:
@IBAction func changeValue(sender: UIDatePicker)
{
//Get time Now, and convert to a NSCalendar
//Specify the minimun date if you want.
let now = NSDate()
let nowCalendar = NSCalendar.currentCalendar()
let nowComponents = nowCalendar.components([.Day, .Month, .Year], fromDate: now)
//Compare if date is lesser than now and then create a new date
if nowCalendar.compareDate(sender.date, toDate: now, toUnitGranularity: [.Day, .Month, .Year]) == NSComparisonResult.OrderedAscending
{
let dateCalendar = NSCalendar.currentCalendar()
let dateComponents = dateCalendar.components([.Day, .Month, .Year], fromDate: sender.date)
dateComponents.year = nowComponents.year + 1
let newDate = dateCalendar.dateFromComponents(dateComponents)
sender.date = newDate!
}
}
答案 1 :(得分:0)
///Swift4 Version - I think it may works with 3 too.
@IBAction func changeValue(sender: UIDatePicker)
{
//Get time Now, and convert to a NSCalendar
//Specify the minimun date if you want.
let now = Date()
let nowCalendar = Calendar.current
let nowComponents = nowCalendar.dateComponents([.day, .month, .year], from: now)
//Compare if date is lesser than now and then create a new date
if nowCalendar.compare(sender.date, to: now, toGranularity: Calendar.Component.day) == ComparisonResult.orderedAscending
{
var dateCalendar = Calendar.current
var dateComponents = dateCalendar.dateComponents([.day, .month, .year], from: sender.date)
guard let year = nowComponents.year else { return }
dateComponents.year = year + 1
let newDate = dateCalendar.date(from:dateComponents)
sender.date = newDate!
}
}
如果你想玩一点,我发表了一个在操场上工作的完整例子。 https://gist.github.com/dedeexe/4878f78d7e1d5fe8b372ef84de629b59
答案 2 :(得分:0)
对于swift 4:
我喜欢这个。 1.我的职能:
func AddDaysToToday(days: Int) -> Date? {
var dateComponents = DateComponents()
dateComponents.day = days
return Func.GetCalendar(tz: .utc).date(byAdding: dateComponents, to: Date()) //you can return your own Date here.
}
在我的VC中:
let today = DateFunc.AddDaysToToday(days: 0)
datePicker.minimumDate = today