xcode iOS 中 UIDatePicker 的默认日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11843185/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Default Date for UIDatePicker in iOS
提问by Ali
I am new in iOS development. I have this ViewController in my Storyboard (includes a UIDatePicker and a bar button):
我是 iOS 开发的新手。我的故事板中有这个 ViewController(包括一个 UIDatePicker 和一个条形按钮):
I followed Data Cellto call my DatePicker. When user click on a button in the page PickerDate pops up with a done bar button on the navigation bar:
我跟着Data Cell调用了我的 DatePicker。当用户单击页面 PickerDate 中的按钮时,导航栏上会弹出一个完成栏按钮:
The problem is it shows just the current date as default
. Nothing changes when I set it from Properties:
问题是它只将当前日期显示为default
. 当我从属性设置它时没有任何变化:
Do you know how can I fix it? (by setting up the properties
or programmatically).
你知道我该如何解决吗?(通过setting up the properties
或以编程方式)。
回答by Ali
I did it programmatically in this way :
我以这种方式以编程方式做到了:
NSCalendar *calendar = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
NSDateComponents *components = [[[NSDateComponents alloc] init] autorelease];
[components setYear:1980];
[components setMonth:1];
[components setDay:1];
NSDate *defualtDate = [calendar dateFromComponents:components];
pickerView.date = defualtDate;
But still don't know why it doesn't work by setting up the properties
. Any help?
但仍然不知道为什么它不起作用setting up the properties
。有什么帮助吗?
回答by King-Wizard
In Swift:
在斯威夫特:
let calendar: NSCalendar = NSCalendar(calendarIdentifier: NSGregorianCalendar)!
calendar.timeZone = NSTimeZone(name: "UTC")!
let components: NSDateComponents = NSDateComponents()
components.year = 1980
components.month = 1
components.day = 1
let defaultDate: NSDate = calendar.dateFromComponents(components)!
self.dateOfBirthUIDatePicker.date = defaultDate
回答by David DelMonte
Great answers above - Here's the Swift3(Feb 17) version:
上面的好答案 - 这是Swift3(2 月 17 日)版本:
let calendar: NSCalendar = NSCalendar(calendarIdentifier: .gregorian)!
calendar.timeZone = NSTimeZone(name: "UTC")! as TimeZone
let components: NSDateComponents = NSDateComponents()
components.year = 1980
components.month = 1
components.day = 1
let defaultDate: NSDate = calendar.date(from: components as DateComponents)! as NSDate
self.datePicker.date = defaultDate as Date