UIDatePicker 更改 "today" 日期的文本颜色

UIDatePicker Change color of text of "today" date

我知道这个问题在其他时候也有人提出过,但是 xCode 7 和 iOS9.2 是否可以更改 UIDatePicker 上 "today" 日期的字体颜色?

[self.dpData setValue:[UIColor colorWithRed:111/255.0f green:113/255.0f blue:121/255.0f alpha:1.0f] forKeyPath:@"setHighlightsToday"];

我试过了,但它崩溃了,所以我知道这行不通。

我还有其他选择吗,或者我真的需要构建自己的 DatePicker?

提前致谢。

查看这个 class 的文档,它的父 class 说它仍然不可能

https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIDatePicker_Class/index.html#//apple_ref/doc/uid/TP40006806

是的,您应该自己制作,因为使用物品选择器是可能的。

这对苹果来说真的很愚蠢

经过更多搜索,我找到了解决方案。

[_dpData setValue:[UIColor colorWithRed:111/255.0f green:113/255.0f blue:121/255.0f alpha:1.0f] forKeyPath:@"textColor"];
SEL selector = NSSelectorFromString( @"setHighlightsToday:" );
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature :
                            [UIDatePicker
                             instanceMethodSignatureForSelector:selector]];
BOOL no = NO;
[invocation setSelector:selector];
[invocation setArgument:&no atIndex:2];
[invocation invokeWithTarget:_dpData];

使用此解决方案,我们可以毫无问题地更改文本的颜色(即使是今天的日期)。

(据报道此方法在 iOS 14 中崩溃,因此不再有效。请参阅下面的讨论。)

一种 safer/easier 方法是简单地设置键“highlightsToday”的值。这是一个 Swift 2.2 示例:

datePicker.setValue(UIColor.whiteColor(), forKey: "textColor")
datePicker.setValue(false, forKey: "highlightsToday")

到目前为止,我使用的是 Richardo 相同的方法,但它使用的是私有 api,它可能始终不可用,否则 Apple 可能会拒绝它。 我只是更改了我的代码(尽管它很笨拙和丑陋),只是将日期选择器更改为不同的模式并返回 - 这会导致 Today 颜色获得之前设置的 textColor。

selectedColor = [UIColor whiteColor];
[self.TimerPicker setValue:selectedColor forKeyPath:@"textColor"];
[self.TimerPicker setDatePickerMode:UIDatePickerModeDate];
[self.TimerPicker setDatePickerMode:UIDatePickerModeDateAndTime];

对我来说足够好了。

即使对于 iOS 13.4 或 14,实际给出的答案仍然是实际的。崩溃的原因是您只能为具有经典 (Wheels) 样式的日期选择器设置这些参数:

datePicker.setValue(UIColor.whiteColor(), forKey: "textColor")
datePicker.setValue(false, forKey: "highlightsToday")

默认情况下,日期选择器具有自动样式:

因此,如果设备安装了 iOS 13.4 或更高版本,它将使用 Compact 样式。但较旧的 iOS 版本将使用 Wheels 样式。

因此,要解决 iOS 13.4 或更高版本的问题,您应该添加一个基于 UIDatePickerStyle 的条件(它从 13.4 开始可用)。像这样:

if #available(iOS 13.4, *) {
            let style = self.startDatePicker.datePickerStyle
            if style == .wheels {
                self.startDatePicker.setValue(UIColor.red, forKey: "textColor")
                self.startDatePicker.setValue(false, forKey: "highlightsToday")
            }
        } else {
            self.startDatePicker.setValue(UIColor.red, forKey: "textColor")
            self.startDatePicker.setValue(false, forKey: "highlightsToday")
        }

另一种方法是使用经典的日期选择器样式 - Wheels,方法是在 StoryBoard 构建器中明确设置它的样式:

不可能,但是您可以在 UIDatePicker 上强制使用深色模式:

if #available(iOS 13.0, *) {
    UIApplication.shared.keyWindow?.overrideUserInterfaceStyle.dark
}