0

I tried to create UIDatePicker without storyboard and let the UILabel of the selected date show, but the label is shown like its being piled up when another date is picked on simulator.

- (void)viewDidLoad {
    [super viewDidLoad];

    UILabel *myLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, 10,100,100)];
    [self.view addSubview:myLabel];

    UIDatePicker *myPicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(10, 10, 200, 200)];

    myPicker.datePickerMode = UIDatePickerModeDate;

    [myPicker addTarget:self action:@selector(pickerChanged:) forControlEvents:UIControlEventValueChanged];

    [self.view addSubview:myPicker]; 
}


- (void)pickerChanged:(id)sender
{
     NSDateFormatter *df = [[NSDateFormatter alloc] init];   
     UILabel *myLabel = [[UILabel alloc]initWithFrame:CGRectMake(50, 300, 200, 200)];

     df.dateFormat = @"yyyy/MM/dd HH:mm";
     myLabel.text = [df stringFromDate:[sender date]];
     [self.view addSubview:myLabel];   
}

The screenshot is as follows: https://i.stack.imgur.com/VnJbD.png

I am a beginner and couldn't find the solution. Can somebody know how to solve this problem? Thank you in advance.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
N I
  • 1
  • 1

2 Answers2

2

This is because you are creating a new label every time the date change

You need to reuse your component, create it in view did load

- (void)viewDidLoad() {
    ....
   self.myLabel = [[UILabel alloc]initWithFrame:CGRectMake(50, 300, 200, 200)];
   [self.view addSubview:self.myLabel];
}

So then you can just set the text:

- (void)pickerChanged:(id)sender {
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    df.dateFormat = @"yyyy/MM/dd HH:mm";
    self.myLabel.text = [df stringFromDate:[sender date]]; 
}
Cyril
  • 361
  • 5
  • 5
0

First add Label in viewDidLoad

 UILabel *myLabel = [[UILabel alloc]initWithFrame:CGRectMake(50, 300, 200, 200)];
   [self.view addSubview:self.myLabel];

and then add date in your Label in PickerChange

self.myLabel.text = [df stringFromDate:[sender date]];