我有一个自定义视图,顶部附有UIDatePicker和完成按钮 .
当我按下完成按钮时,我想得到 time that is in the 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);
图片参考:
4 回答
编写没有参数的方法,并将
UIDatePicker
作为整个类的属性或全局对象,以便可以从任何位置访问它 .现在通过这种方式将您的方法传递给两个选择器,您将按完成按钮实现日期 .
你是什么导致这个崩溃是正确的 . 我认为将选择器分开是正确的道路 . 您可以让两个选择器调用相同的方法 . 这样你就没有任何复制的代码 .
TIME
正确的方法是创建一个
NSDate
对象,可以根据您的要求访问该对象 . 现在从UIDatePicker
,创建一个值已更改的方法 . 每当调用此方法时,将日期选择器.date
属性的值设置为NSDate
对象 . 按完成按钮后,使用NSDate
对象的值 . 它会给你正确的 Value .