1

In my app I use UIDatePicker with custom text color and on iOS 12/13 this code works fine:

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

But on iOS 14 my app crashed.

Stacktrace:

-[_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

Does anyone know how can I use custom text color on iOS 14+?

Robot Bender
  • 85
  • 10
  • 1
    Just FYI https://stackoverflow.com/a/39553039/1801544 just in case. You might want to check in debugger if you can see some hidden values. But this could be a temporary bug resolved in future stable iOS14 versions. – Larme Jul 09 '20 at 17:52

3 Answers3

2

Using KVC is unsafe in swift because if the key is missing, your application will crash. In order to change the color of the text in UIDatePicker, using the property tintColor.

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

This may only available for preferredDatePickerStyle = .wheels

So you can add this below check

     if #available(iOS 13.4, *) {
        <yourPickerview>.preferredDatePickerStyle = .wheels
    } else {
        // Fallback on earlier versions
    }
Murugan M
  • 175
  • 3
  • 8
0

As I replied in the answer Larme linked, textColor is a private property of UIDatePicker. There's no guarantee that it will exist in any version of iOS, so what you are doing is not safe.

KVC lets you try to change properties of an object without any compile-time checking, so if the property gets removed, you crash.

Duncan C
  • 128,072
  • 22
  • 173
  • 272
  • I understand that it is not safe. But my goal is to use custom UI for the system date picker. – Robot Bender Jul 09 '20 at 18:24
  • @RobotBender The safest way is to create your own UIDatePicker, else you might have possible crash at each iOS update. – Larme Jul 10 '20 at 08:33