我的UIDatePicker背景是黑色的(可能因为整个屏幕的背景都是黑色),但我想要将UIDatePicker的背景改成白色。
有没有办法在不对其进行子类化的情况下更改背景颜色?
我的UIDatePicker背景是黑色的(可能因为整个屏幕的背景都是黑色),但我想要将UIDatePicker的背景改成白色。
有没有办法在不对其进行子类化的情况下更改背景颜色?
iOS 14更新
在iOS 14中,看起来datePicker.backgroundColor
不起作用,但实际上它是可以生效的。只是你需要在设置preferredDatePickerStyle
之后设置:
let picker = UIDatePicker()
if #available(iOS 13.4, *) {
picker.preferredDatePickerStyle = .wheels
}
picker.backgroundColor = .red
datePickerName.backgroundColor = [UIColor grayColor];
OBJECTIVE C
datePicker.backgroundColor = [UIColor greenColor]
SWIFT
DatePicker.backgroundColor = UIColor.blueColor()
DatePicker.setValue(UIColor.greenColor(), forKeyPath: "textColor")
DatePicker.setValue(0.8, forKeyPath: "alpha")
iOS 14更新
iOS 14更新后,可以通过以下方式设置背景颜色:
datePicker.backgroundColor = <# your bg color #>
不再起作用了。
所以我现在使用键值编码方法:
datePicker.setValue(<# your bg color #> , forKey: "backgroundColor")
datePickerBackground = [[UIView alloc] initWithFrame:myDatePickerView.frame];
datePickerBackground.backgroundColor = [UIColor whiteColor];
[self.view insertSubview:datePickerBackground belowSubview:myDatePickerView];
我在我的类中声明了UIView *datePickerBackground;。由于我重用同一个视图控制器,因此我在unLoad时将datePickerBackground设置为nil。
只需按照以下步骤操作:
首先在.h文件中设置delegate,例如:
UIPickerViewDelegate, UIPickerViewDataSource
然后在创建datepicker时添加该行代码:
YourDatePicker = [[UIDatePicker alloc] init];
YourDatePicker.backgroundColor=[UIColor whiteColor];
在您的情况下,颜色为白色,但您可以根据需要更改它。
yourDatePickerRef.backgroundColor = [UIColor whiteColor];
来编程设置背景。但事实证明,根据这个相关问题,UIDatePicker有许多子视图内部,其中一些是背景视图。UIView
。将视图的背景颜色设置为白色。将视图的框架设置为与选择器相同。
datePicker.backgroundColor
在 iOS 14 中有效。但你必须把它放在picker.preferredDatePickerStyle = .wheels
的后面。 - goodliving