簡體   English   中英

帶有最小日期的Swift Datepicker

[英]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.
}
  1. 在我的VC中:

     let today = DateFunc.AddDaysToToday(days: 0) datePicker.minimumDate = today 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM