質問

I have this code which adds a UIDatepicker (datePicker) when the UITextField (dateDue) is tapped:

In the 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:

- (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. 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.

In viewDidLoad, change:

UIDatePicker *datePicker = [[UIDatePicker alloc] init];

to:

datePicker = [[UIDatePicker alloc] init];

That will fix it.

You should also change your dateChanged: method to:

- (void) dateChanged:(UIDatePicker *)picker {
    // Add the date to the dueDate text field
    NSLog(@"Date changed: %@", picker.date);
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top