首页 > 解决方案 > 通过 KVC 设置“textColor”时,UIDatePicker 在 iOS 14 上崩溃

问题描述

在我的应用程序中,我使用UIDatePicker自定义文本颜色,在 iOS 12/13 上,此代码工作正常:

timePicker.setValue(UIColor.red, forKeyPath: "textColor")

但在 iOS 14 上,我的应用程序崩溃了。

堆栈跟踪:

-[_UIDatePickerIOSCompactView _setTextColor:]: unrecognized selector sent to instance 0x7ff09265a8c0
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[_UIDatePickerIOSCompactView _setTextColor:]: unrecognized selector sent to instance 0x7ff09265a8c0'
*** First throw call stack:
(
    0   CoreFoundation                      0x000000011b0eea2a __exceptionPreprocess + 242
    1   libobjc.A.dylib                     0x000000011aa004ce objc_exception_throw + 48
    2   CoreFoundation                      0x000000011b0fd579 +[NSObject(NSObject) instanceMethodSignatureForSelector:] + 0
    3   UIKitCore                           0x00000001235db925 -[UIResponder doesNotRecognizeSelector:] + 292
    4   CoreFoundation                      0x000000011b0f2cf4 ___forwarding___ + 859
    5   CoreFoundation                      0x000000011b0f4f98 _CF_forwarding_prep_0 + 120
    6   Foundation                          0x0000000110c0a6ae -[NSObject(NSKeyValueCoding) setValue:forKey:] + 325
    7   UIKitCore                           0x0000000123af85c5 -[UIView(CALayerDelegate) setValue:forKey:] + 171

有谁知道如何在 iOS 14+ 上使用自定义文本颜色?

标签: iosswiftuikituidatepickerios14

解决方案


在 swift 中使用 KVC 是不安全的,因为如果缺少密钥,您的应用程序将崩溃。为了改变 UIDatePicker 中文本的颜色,使用属性 tintColor。

var picker = UIDatePicker()
picker.tintColor = UIColor.blue

推荐阅读