簡體   English   中英

為什么UIDatePicker值為null?

[英]Why is the UIDatePicker value null?

我有這段代碼,當點擊UITextField(dateDue)時添加了一個UIDatepicker(datePicker):

在viewDidLoad中:

// Initiate datepicker and assign to due date
UIDatePicker *datePicker = [[UIDatePicker alloc] init];
[datePicker addTarget:self action:@selector(dateChanged:)
 forControlEvents:UIControlEventValueChanged];
_dueDate.inputView = datePicker;

它很好用,但是我似乎無法在changedDate函數中獲取日期值,它一直返回null:

- (void) dateChanged:(id)sender{
    // Add the date to the dueDate text field
    NSLog(@"Date changed: %@", datePicker.date);
}

有誰知道為什么會這樣嗎?

彼得

在您的dateChanged:方法中,您正在訪問一個名為datePicker的變量。 這是實例變量嗎?

假設它是您從未設置過。 viewDidLoad您有一個名為datePicker的局部變量,該變量與具有相同名稱的實例變量不同。

viewDidLoad ,更改:

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

至:

datePicker = [[UIDatePicker alloc] init];

這將解決它。

您還應該將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.

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