[英]Why is the UIDatePicker value null?
I have this code which adds a UIDatepicker (datePicker) when the UITextField (dateDue) is tapped: 我有这段代码,当点击UITextField(dateDue)时添加了一个UIDatepicker(datePicker):
In the viewDidLoad: 在viewDidLoad中:
// Initiate datepicker and assign to due date
UIDatePicker *datePicker = [[UIDatePicker alloc] init];
[datePicker addTarget:self action:@selector(dateChanged:)
forControlEvents:UIControlEventValueChanged];
_dueDate.inputView = datePicker;
It works great, but I can't seem to get the date value in the changedDate function, it keeps returning null: 它很好用,但是我似乎无法在changedDate函数中获取日期值,它一直返回null:
- (void) dateChanged:(id)sender{
// Add the date to the dueDate text field
NSLog(@"Date changed: %@", datePicker.date);
}
Does anyone have any idea why this is happening? 有谁知道为什么会这样吗?
Peter 彼得
In your dateChanged:
method you are accessing a variable named datePicker
. 在您的
dateChanged:
方法中,您正在访问一个名为datePicker
的变量。 Is this an instance variable? 这是实例变量吗?
Assuming it is, you never set it. 假设它是您从未设置过。 In your
viewDidLoad
you have a local variable named datePicker
that you use but that is different from the instance variable with the same name. 在
viewDidLoad
您有一个名为datePicker
的局部变量,该变量与具有相同名称的实例变量不同。
In viewDidLoad
, change: 在
viewDidLoad
,更改:
UIDatePicker *datePicker = [[UIDatePicker alloc] init];
to: 至:
datePicker = [[UIDatePicker alloc] init];
That will fix it. 这将解决它。
You should also change your dateChanged:
method to: 您还应该将
dateChanged:
方法更改为:
- (void) dateChanged:(UIDatePicker *)picker {
// Add the date to the dueDate text field
NSLog(@"Date changed: %@", picker.date);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.