以编程方式为UIDatePicker设置样式

时间:2017-12-15 11:16:24

标签: objective-c colors uidatepicker

我有一个包含年龄的注册表单,当用户输入他们的年龄时,会弹出一个UIDatePicker,他们可以选择一个日期。我在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.backgroundColor& datePicker.tintColor似乎没有做任何事情。这是文本域的图像,

Popup UIDatePicker

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

1 个答案:

答案 0 :(得分:0)

好的,我已经弄明白了如何设置颜色,在这种情况下你不能使用.backgroundColor.tintColor属性。相反,你必须设置key的值(与环境变量相同!

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

和设置背景̶c̶o̶l̶o̶u̶r̶̶(之后的无奈)̶我发现可以设置一个背景̶c̶o̶l̶o̶u̶r̶上的日期̶p̶i̶c̶k̶e̶r̶'̶s̶层̶(DUH)̶,̶̶̶̶̶̶_ 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̶r̶e̶c̶t̶l̶y̶!̶

上面的解决方案确实设置了背景颜色但不是正确的颜色(它有白色调),我不能在我的生活中找到负责的层。我发现我的文本字段配置错误(样式设置为暗而不是默认值),以设置必须将键盘设置为默认值的背景颜色。

_datePicker.backgroundColor = kBackgroundColor1;

enter image description here

然后你的日期选择器会看起来很漂亮和喜欢这样: enter image description here