OGeek|极客世界-中国程序员成长平台

标题: ios - 具有最短日期的 Swift Datepicker [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 11:34
标题: ios - 具有最短日期的 Swift Datepicker

大家早上好,

我有一个带有 ios 8 和 swift 的应用程序。 在 UIDatepicker

中有一个 UIViewcontroller

我设置了一个最短日期。例如今天的日期:2 |五月 | 2015 使用此解决方案,应该无法设置过去的日期

但如果想将此日期设置为 15 |一月 | 2016 年 我一开始将日期设置为 15 比一个月到 1 月,但随后 UIDatepicker 回到最短日期 2015 年 5 月 2 日

是否有可能,将日期更改为 15 并将月份更改为一月,年份会自动更改为 2016 年?



Best Answer-推荐答案


让你的 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!
    }

}

关于ios - 具有最短日期的 Swift Datepicker,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32347688/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4