DatePicker值在更改后不会更改

时间:2012-08-21 11:54:51

标签: iphone datepicker xcode4.2

-(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的Doc.Based中的UIDatePicker Class引用,因为我已经实现了上面的代码。当我在按钮操作中写入外部方法代码而不是更改日期时,我只获得按钮上的当前日期在DatePicker中更改。

如果我像上面提到的那样编写代码,我甚至可以在按钮上获得任何标题。 我想,我犯了大错的错误,任何人都可以告诉我错误在哪里并详细解释我。

非常感谢您提前获得帮助。

2 个答案:

答案 0 :(得分:4)

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

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

(见reference)。

然后实现方法:

- (void)dateChanged:(UIDatePicker*)datePicker {
    NSLog("Date changed: %@", datePicker.date);
}

答案 1 :(得分: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);

   }