[英]Swift Datepicker with minimum date
Goord Morning在一起,
我有一个iOS 8和Swift的应用程序。 在UIViewcontroller
中有一个UIDatepicker
我设定了最低日期。 例如今天的日期:2 | 五月 使用此解决方案的2015年,应该无法设置过去的日期
但如果要将此日期设置为15 | 一月 2016年我将第一天设置为比一月的第一天15,但随后UIDatepicker
返回最短日期2015年5月2日
我们是否有可能将日期更改为15,将月份更改为一月,将年份自动更改为2016?
让您的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!
}
}
///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
快速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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.