Setting frame to Date picker in iOS7

2019-02-21 08:00发布

问题:

I am able to set date picker frame from Storyboard. But I am not able to set the frame programatically. I would like to no why datePicker.frame is not working even though setFrame: functionality is not deprecated in iOS7. Also please provide a way to set date picker frame programatically. Any help is greatly appreciated.

回答1:

If you have already added UIDatePicker to .nib or .storyboard file and would like to update frame programatically, then you can update frame inside viewDidLayoutSubviews method in your view controller. I just tried to update frame and it worked on iOS 7.0

- (void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];

    self.datePicker.frame = CGRectMake(0, 50, 300, 162);
}

If want to add a date picker programatically in view controller then you can try creating a date picker in viewDidLoad method and add it to subview.

UIDatePicker *datePicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(0, 300, 300, 162)];
[self.view addSubview:datePicker];