You need to enable JavaScript to run this app. iOS14.4中作为UITextField键盘的Date picker view尺寸过小如何解决
优惠活动
大模型
产品
解决方案
定价
更多

iOS14.4中作为UITextField键盘的Date picker view尺寸过小如何解决

UIDatePicker作为UITextField输入视图在iOS14.4下尺寸异常修复方案

问题根因

从iOS13.4版本开始,苹果为UIDatePicker新增了preferredDatePickerStyle属性,默认值为UIDatePickerStyle.automatic,系统会根据使用场景自动切换显示样式。iOS14.4版本中,该自动样式在作为UITextField的inputView加载时,会出现系统布局计算错误,最终导致控件尺寸极小。

修复方案

可根据业务需求选择以下任意一种方案修复:

  • 方案1:强制指定为旧版滚轮样式(最稳妥无兼容问题)
    该方案可让控件表现和iOS13.4之前完全一致,无需额外调整布局:
    Swift代码

    let datePicker = UIDatePicker()
    if #available(iOS 13.4, *) {
        datePicker.preferredDatePickerStyle = .wheels
    }
    yourTextField.inputView = datePicker
    

    Objective-C代码

    UIDatePicker *datePicker = [[UIDatePicker alloc] init];
    if (@available(iOS 13.4, *)) {
        datePicker.preferredDatePickerStyle = UIDatePickerStyleWheels;
    }
    yourTextField.inputView = datePicker;
    
  • 方案2:手动设置控件固定尺寸(适合需要使用新版样式的场景)
    如果你需要使用iOS14之后新增的紧凑/内嵌样式,可主动给控件指定尺寸:

    // 可根据业务需求调整宽高数值
    datePicker.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 320)
    // 若使用AutoLayout,可添加宽高约束
    datePicker.widthAnchor.constraint(equalToConstant: UIScreen.main.bounds.width).isActive = true
    datePicker.heightAnchor.constraint(equalToConstant: 320).isActive = true
    
  • 方案3:使用容器视图包裹
    新增一个普通UIView作为容器,将datePicker添加到容器中并设置约束撑满容器,再将容器设置为inputView,即可规避系统自动布局的异常问题。


内容的提问来源于stack exchange,提问作者Sky Clones

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.12 14:27:01