以编程方式设置 UIDatePicker 的样式

Styling UIDatePicker Programmatically

我有一个包含年龄的注册表单,当用户输入他们的年龄时,会弹出一个 UIDatePicker,他们可以 select 一个日期。我是运行在viewDidLoad下面的代码实现的:

- (void)configureAgePicker {

    //Initialise date picker
    UIDatePicker *datePicker = [[UIDatePicker alloc] init];
    datePicker.datePickerMode = UIDatePickerModeDate;
    datePicker.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_UK"];

    //Add toolbar to keyboard
    UIToolbar *toolBar=[[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 44)];
    UIBarButtonItem *doneBtn=[[UIBarButtonItem alloc]initWithTitle:@"Done" style:UIBarButtonItemStylePlain target:self action:@selector(resignKeyboards)];
    UIBarButtonItem *space=[[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
    [toolBar setItems:[NSArray arrayWithObjects:space,doneBtn, nil]];

    //style popup
    toolBar.barTintColor = kPrimaryHighlightGradient;
    datePicker.backgroundColor = kPrimaryHighlight;
    datePicker.tintColor = kTextColor4;

    self.ageTextfield.inputAccessoryView = toolBar;
    self.ageTextfield.inputView = datePicker;

}

我的问题是我无法更改日期选择器本身的颜色属性。我可以设置工具栏的颜色(效果很好)但是 datePicker.backgroundColordatePicker.tintColor 似乎没有做任何事情。这是文本字段的图像,

我真的很想更改此弹出窗口的颜色以匹配我的应用程序的配色方案。我之前通过故事板设置了 UIDatePickers 的样式,并记得必须使用运行时变量来设置配色方案(我不能通过代码)。由于我是通过代码创建这个日期选择器并将其添加到文本字段键盘,我还需要做更多的事情来更改配色方案吗?

好的,所以我知道如何设置颜色,在这种情况下您不能使用 .backgroundColor.tintColor 属性。相反,您必须设置 key 的值(与环境变量相同!

[datePicker setValue:kTextColor4 forKey:@"textColor"];

A̶n̶d̶ ̶t̶o̶ ̶s̶e̶t̶ ̶t̶h̶e̶ ̶b̶a̶c̶k̶g̶r̶o̶u̶n̶d̶ ̶c̶o̶l̶o̶u̶r̶ ̶(̶a̶f̶t̶e̶r̶ ̶m̶u̶c̶h̶ ̶f̶r̶u̶s̶t̶r̶a̶t̶i̶o̶n̶)̶ ̶I̶ ̶f̶o̶u̶n̶d̶ ̶y̶o̶u̶ ̶c̶a̶n̶ ̶s̶e̶t̶ ̶a̶ ̶b̶a̶c̶k̶g̶r̶o̶u̶n̶d̶ ̶c̶o̶l̶o̶u̶r̶ ̶o̶n̶ ̶t̶h̶e̶ ̶d̶a̶t̶e̶ ̶p̶i̶c̶k̶e̶r̶'̶s̶ ̶l̶a̶y̶e̶r̶ ̶(̶d̶u̶h̶)̶,̶ ̶ ̶ ̶ ̶ ̶ ̶_̶d̶a̶t̶e̶P̶i̶c̶k̶e̶r̶.̶l̶a̶y̶e̶r̶.̶b̶a̶c̶k̶g̶r̶o̶u̶n̶d̶C̶o̶l̶o̶r̶ ̶=̶ ̶k̶B̶a̶c̶k̶g̶r̶o̶u̶n̶d̶C̶o̶l̶o̶r̶1̶.̶C̶G̶C̶o̶l̶o̶r̶;̶ ̶̶N̶o̶w̶̶m̶y̶̶d̶a̶t̶e̶p̶i̶c̶k̶e̶r̶̶p̶o̶p̶u̶p̶̶i̶s̶̶s̶t̶y̶l̶e̶d̶̶c̶o̶r̶o̶=e̶7̶[1̶c]

上面的解决方案确实设置了背景颜色,但没有设置正确的颜色(它有一种偏白的色调),我终究找不到负责的图层。我发现我的文本字段配置错误(样式设置为深色而不是默认值)以设置背景颜色,您必须将键盘设置为默认值。

_datePicker.backgroundColor = kBackgroundColor1;

然后你的日期选择器看起来会像这样漂亮和花哨: