【问题标题】:Issues with Adding UIDatePicker to UIView at Runtime在运行时将 UIDatePicker 添加到 UIView 的问题
【发布时间】:2025-12-31 19:00:01
【问题描述】:

当用户单击按钮时,我正在尝试将 UIDatePicker 添加到 UIView。我有一个动画设置,可以从底部向上滑动 UIView。如果我将 UIDatePicker 添加到 ViewControllers 视图,则 DatePicker 会正确显示。但是,如果我将 DatePicker 添加到 UIView 则日期选择器根本不会显示。

- (IBAction)setTimeButtonPressed:(UIButton *)sender
{
    // Creates Frame Rects for views and controls
    CGRect datePickerViewOutFrame = CGRectMake(0, 336, self.view.frame.size.width, 228);
    CGRect datePickerOutFrame = CGRectMake(0, 336, self.view.frame.size.width, 162);

    // Create View that will slide out
    UIView *datePickerView = [[UIView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height, self.view.frame.size.width, 0)];
    datePickerView.backgroundColor = [UIColor flatCloudsColor];

    // Setup DatePicker
    UIDatePicker *datePicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height, self.view.frame.size.width, 0)];
    datePicker.datePickerMode = UIDatePickerModeTime;
    datePicker.date = [NSDate date];
    datePicker.hidden = NO;

    [self.view addSubview:datePickerView]; 
    [datePickerView addSubview:datePicker]; /* DOES NOT WORK*/

    self.datePickerView.clipsToBounds = YES;

    // Animate the views sliding out from the bottom
    [UIView animateWithDuration:0.5
                          delay:0
                        options:UIViewAnimationOptionCurveLinear
                     animations:^{
                         datePicker.frame = datePickerOutFrame;
                         datePickerView.frame = datePickerViewOutFrame;

                     }
                     completion:^(BOOL finished){
                         // Might need later
                     }];
}

但是,如果我更改添加 datePicker 的行,它可以工作,但我无法将它剪辑到 datePickerView 的边界。

[self.view addSubview:datePickerView];
[self.view addSubview:datePicker];  /* Works but can't clip DatePicker */

我做错了什么?

【问题讨论】:

    标签: ios objective-c cocoa-touch uidatepicker


    【解决方案1】:

    UIDatePickerView 框架需要相对于其父视图。所以如果你想把它添加到你的datePickerViewUIDatePicker 的框架应该有一个0,0 的原点,而不是基于视图控制器视图的高度。

    UIDatePicker *datePicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 0)];
    

    【讨论】:

    • 啊哈,我知道我错过了什么。谢谢,成功了!