Search code examples
objective-cios6uidatepicker

Positioning UIDatePicker


Part of my UIDatePicker is extending off the bottom of the screen even though I think I am positioning it correctly. Can someone tell me what I am doing wrong? I've gone through the following lines multiple tines and can't figure out where I went wrong. I'm trying to avoid explicitly specifying coordinates for my UIDatePicker's frame. I've included the relevant code from my view controller here:

// Create the time picker
self.timePicker = [[UIDatePicker alloc] init];
[self.timePicker addTarget:self action:@selector(datePickerDateChanged:) forControlEvents:UIControlEventValueChanged];
self.timePicker.datePickerMode = UIDatePickerModeTime;

// Set the time picker frame
CGRect screenRect = [self.view frame];
CGSize pickerSize = [self.timePicker sizeThatFits:CGSizeZero];
CGRect pickerRect = CGRectMake(screenRect.origin.x,
                               screenRect.origin.y + screenRect.size.height - pickerSize.height,
                               pickerSize.width,
                               pickerSize.height);
NSLog(@"Picker frame: %f", screenRect.size.height);
NSLog(@"Picker frame: %f", screenRect.origin.y + screenRect.size.height - pickerSize.height);
[self.timePicker setFrame:pickerRect];

// Add the picker to the view
[self.view addSubview:self.timePicker];

Solution

  • There are a few issues.

    Since you want the picker view to be placed relative to self.view you want screenRect to be based on self.view.bounds, not self.view.frame.

    Also, never call sizeThatFits:. Call sizeToFit instead. This is stated in the docs for one of those two methods. But this isn't necessary. The picker view will automatically be the proper size.

    Most likely you want the picker view to fill the width of the view (at least on an iPhone/iPod touch). So your pickerRect should be:

    CGSize pickerSize = self.timePicker.bounds.size;
    CGRect pickerRect = CGRectMake(0,
                                   screenRect.size.height - pickerSize.height,
                                   screenRect.size.width,
                                   pickerSize.height);
    

    The last step is to set the autoresizing mask for the picker. Since you want the picker pinned to the bottom of the view you should set it up with a flexible top margin. And since you want it the width of the view set it to flexible width:

    self.timePicker.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth;