Xcode - UIDatePicker背景颜色

7

enter image description here我的UIDatePicker背景是黑色的(可能因为整个屏幕的背景都是黑色),但我想要将UIDatePicker的背景改成白色。

有没有办法在不对其进行子类化的情况下更改背景颜色?

8个回答

6

iOS 14更新

在iOS 14中,看起来datePicker.backgroundColor不起作用,但实际上它是可以生效的。只是你需要在设置preferredDatePickerStyle之后设置:

let picker = UIDatePicker()
if #available(iOS 13.4, *) {
    picker.preferredDatePickerStyle = .wheels
}
picker.backgroundColor = .red

5
datePickerName.backgroundColor = [UIColor grayColor];

3

OBJECTIVE C

datePicker.backgroundColor = [UIColor greenColor]

SWIFT

DatePicker.backgroundColor = UIColor.blueColor()
DatePicker.setValue(UIColor.greenColor(), forKeyPath: "textColor")
DatePicker.setValue(0.8, forKeyPath: "alpha")

2

iOS 14更新

iOS 14更新后,可以通过以下方式设置背景颜色:

datePicker.backgroundColor = <# your bg color #> 

不再起作用了。

所以我现在使用键值编码方法:

datePicker.setValue(<# your bg color #> , forKey: "backgroundColor")

1
datePicker.backgroundColor 在 iOS 14 中有效。但你必须把它放在 picker.preferredDatePickerStyle = .wheels 的后面。 - goodliving

1
我遇到了同样的问题。我只是创建了一个UIView,并将其放在UIDatePicker后面。
    datePickerBackground = [[UIView alloc] initWithFrame:myDatePickerView.frame];
    datePickerBackground.backgroundColor = [UIColor whiteColor];
    [self.view insertSubview:datePickerBackground belowSubview:myDatePickerView];

我在我的类中声明了UIView *datePickerBackground;。由于我重用同一个视图控制器,因此我在unLoad时将datePickerBackground设置为nil。


1

只需按照以下步骤操作:

  • 首先在.h文件中设置delegate,例如:

    UIPickerViewDelegate, UIPickerViewDataSource

  • 然后在创建datepicker时添加该行代码:

    YourDatePicker = [[UIDatePicker alloc] init];
    YourDatePicker.backgroundColor=[UIColor whiteColor];

  • 在您的情况下,颜色为白色,但您可以根据需要更改它。


0

谢谢!我刚刚浏览了这个子视图的所有层。我需要更改对象索引-4、10和16以获得正确的颜色。希望苹果不会改变顺序... :P - Rocky

0
为选择器添加一个简单的 UIView。将视图的背景颜色设置为白色。将视图的框架设置为与选择器相同。
注意(根据您对Michael答案的评论):
在UIDatePicker的私有子视图中进行挖掘是冒险的。它随时可能出错。几乎可以肯定,如果日期选择器在不使用AM / PM的区域设置的设备上使用,则您的解决方案将会出错,因为选择器只有两个组件而不是三个。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接