【问题标题】:Why is the UIDatePicker value null?为什么 UIDatePicker 值为空?
【发布时间】:2014-03-24 07:22:46
【问题描述】:

我有这段代码,它在点击 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);
}

有人知道为什么会这样吗?

彼得

【问题讨论】:

    标签: ios objective-c uidatepicker


    【解决方案1】:

    在您的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);
    }
    

    【讨论】:

    • 当我更改代码时出现错误:“使用未声明的标识符 'datePicker';您的意思是 '_datePicker'?”
    • 您有日期选择器的属性吗?如果是这样,请使用self.datePicker
    • 在 .h 文件中?不,我没有,因为它是以编程方式创建的
    • 那么在您的dateChanged: 方法中访问的datePicker 变量是什么?
    • 不确定,但我合成了 datPicker var,这似乎可以做到。我想通过代码“UIDatePicker *datePicker = [[UIDatePicker alloc] init];”这将使 datePicker 变量随处可用。
    猜你喜欢
    • 2019-08-21
    • 2021-05-11
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    • 2014-02-18
    • 1970-01-01
    • 1970-01-01
    • 2014-11-02
    相关资源
    最近更新 更多