Minimum and maximum date in UIDatePicker

前端 未结 11 1286
不知归路
不知归路 2020-11-30 00:34

I want to get the minimum and maximum date from a date picker, but minimum date should be \"- 18\" of the current date and the maximum date should be \"- 100\" of current da

11条回答
  •  感情败类
    2020-11-30 01:09

    Swift 4.1

    I have created my extension for all type of limit based on Calendar.Component

    extension UIDatePicker {
    
        func setLimit(forCalendarComponent component:Calendar.Component, minimumUnit min: Int, maximumUnit max: Int) {
    
            let currentDate: Date = Date()
            var calendar: Calendar = Calendar(identifier: Calendar.Identifier.gregorian)
    
            guard let timeZone = TimeZone(identifier: "UTC") else { return }
            calendar.timeZone = timeZone
    
            var components: DateComponents = DateComponents()
            components.calendar = calendar
    
            components.setValue(-min, for: component)
            if let maxDate: Date = calendar.date(byAdding: components, to: currentDate) {
                self.maximumDate = maxDate
            }
    
            components.setValue(-max, for: component)
            if let minDate: Date = calendar.date(byAdding: components, to: currentDate) {
                self.minimumDate = minDate
            }
        }
    
    }
    

    We can use this as following:

    self.datePicker.setLimit(forCalendarComponent: .year, minimumUnit: 13, maximumUnit: 100)
    

提交回复
热议问题