3
-(IBAction)showDate:(id)sender
{
datePicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(0, 220, 325, 300)];
datePicker.datePickerMode = UIDatePickerModeDate;
datePicker.hidden = NO;
datePicker.date = [NSDate date];
[datePicker setDate:datePicker.date animated:YES];
[self.view addSubview:datePicker];
}



- (void)setDate:(NSDate *)date animated:(BOOL)animated
{
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"dd/MM/yyyy"];
NSString *str = [df stringFromDate:date];
NSLog(@"String is------:%@",str);
[dateBtn setTitle:str forState:UIControlStateNormal];
}

我已经通过了 Apple 文档中的 UIDatePicker 类参考。基于此,我已经实现了上述代码。当外部方法代码以按钮操作写入时,我只获得按钮上的当前日期,如果我更改 DatePicker,则不会更改日期.

如果我编写如上所述的代码,我什至无法在按钮上获得任何标题。我想,我犯了一个错误的错误,谁能告诉我错误在哪里并详细解释我。

非常感谢您提前提供帮助。

4

2 回答 2

4

我认为您对子类化感到困惑,这是您在这里没有做的事情(也不需要)。您需要设置日期选择器以在日期更改时调用您选择的方法;像这样的东西:

[datePicker addTarget:self
               action:@selector(dateChanged:)
     forControlEvents:UIControlEventValueChanged];

(见参考)。

然后实现方法:

- (void)dateChanged:(UIDatePicker*)datePicker {
    NSLog("Date changed: %@", datePicker.date);
}
于 2012-08-21T12:02:55.623 回答
0

试试这个代码:

-(void)timepicker:(UIGestureRecognizer *)date{

    CGRect pickerFrame = CGRectMake(0,200,0,0);

    myPicker = [[UIDatePicker alloc] initWithFrame:pickerFrame];
    [myPicker setBackgroundColor:[UIColor groupTableViewBackgroundColor]];
    [myPicker addTarget:self action:@selector(pickerChanged:)               forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:myPicker];


}
- (void)pickerChanged:(id)sender{

    NSLog(@"value: %@",[sender date]);

    NSDateFormatter *df = [[NSDateFormatter alloc] init];

    df.dateStyle = NSDateFormatterMediumStyle;

    NSString *date=[NSString stringWithFormat:@"%@",[sender date]];

    NSLog(@"value1: %@",date);

   }
于 2014-03-06T05:44:53.457 回答