如何更改标签上的datepicker选定值

时间:2012-10-24 07:36:41

标签: objective-c ios xcode

我想在标签上显示来自datepicker的所选日期,但标签只显示当前日期,它没有显示我从datepicker中选择的日期这是代码,请告诉我如何更改文本标签使用datepicker中随机选择的日期

#import "ViewController.h"

@implementation ViewController
@synthesize datepicker,mylabel;


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    NSDate *chosen = datepicker.date;
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    formatter.dateStyle = NSDateFormatterMediumStyle;
    mylabel.text = [formatter stringFromDate:chosen];
     [formatter release];    

    // Do any additional setup after loading the view, typically from a nib.

}

- (void)viewDidUnload
{

    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

@end

1 个答案:

答案 0 :(得分:3)

    // code for Date picker for current date

     datepicker=[[UIDatePicker alloc]initWithFrame:CGRectMake(0, 200, 320, 150)];
        //[self.view addSubview:datepicker];
        datepicker.date = [NSDate date];
        datepicker.datePickerMode=UIDatePickerModeDate;
        NSDateFormatter *df = [[NSDateFormatter alloc] init];
        df.timeStyle = NSDateFormatterNoStyle;

        label.text=[NSString stringWithFormat:@"%@",
                   [df stringFromDate:[NSDate date]]];
        df.dateFormat = @"yyyy-MM-dd";

    // set action for date picker

       [datepicker addTarget:self  action:@selector(DateChange:)
            forControlEvents:UIControlEventValueChanged];

    //method for change date

    - (void)DateChange:(id)sender
{
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"dd-MM-yyyy"];
        label.text = [dateFormatter stringFromDate:datepicker.date];
        date.text=strDate;
}