我有一个自定义视图,其顶部带有UIDatePicker和完成按钮。
当我按下完成按钮时,我想获取UIDatePicker中的时间。
按下按钮时会收到错误消息(由于发件人是UIBarButtonItem,所以我希望如此),并且更改日期时间可以按预期工作。
其他解决方案显示了单独的选择器,但是,我希望(如果可能)调用相同的选择器,并像在选择器视图中滚动一样获取选定的选择器。
我考虑过更改选择器方法以将其作为id
接收,但这没有用。
这是我目前正在做的事情,我觉得这可能很愚蠢:
UIView *v = [[UIView alloc] init];
// Create the date time picker
CGRect pickerFrame = CGRectMake(0, 0, 320, 216);
UIDatePicker *pView = [[UIDatePicker alloc] initWithFrame:pickerFrame];
pView.datePickerMode = UIDatePickerModeTime;
[pView addTarget:self action:@selector(dateTimePickerValueChanged:) forControlEvents:UIControlEventValueChanged];
dateTimePicker = pView;
[v addSubview:dateTimePicker];
// done button
CGRect toolBarFrame = CGRectMake(0, 0, 320, 44);
UIToolbar *toolBar = [[UIToolbar alloc] initWithFrame:toolBarFrame];
UIBarButtonItem *flexibleItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
UIBarButtonItem *doneButton = [[UIBarButtonItem alloc] initWithTitle:@"Done" style:UIBarButtonItemStylePlain target:self action:@selector(dateTimePickerValueChanged:)];
NSArray *toolBarItems = [NSArray arrayWithObjects:flexibleItem, doneButton, nil];
[toolBar setItems:toolBarItems];
[v addSubview:toolBar];
- (void)dateTimePickerValueChanged:(UIDatePicker *)datePicker {
NSLog(@"time on change: %@", datePicker.date);
图片参考:
最佳答案
编写不带参数的方法,并使UIDatePicker
作为整个类的属性或全局对象,以便您可以从任何位置访问它。
现在以这种方式将您的方法传递给两个选择器,您将在完成按钮按下时获得日期。
- (void)dateTimePickerValueChanged {
NSLog(@"time on change: %@", datePicker.date);
}
关于ios - 在“完成”按钮上按UIDatePicker获取.date属性,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41557445/