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 = datePickerObjective-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
相关产品推荐
相关产品推荐

