iosobjective-ccocoa-touchdatepickeruikit

How do I monitor the fitting width change of an UIDatePicker on iOS using UIKit?


I'd like to monitor the fitting width of an UIDatePicker set to the mode of .date on iOS. By fitting width, I mean that usually obtained by systemLayoutSizeFittingSize(CGSize(0, 0)) -- but I need to monitor its change and get the value of it after the change.

I know that it is possible to use UIControlEventValueChanged to monitor the change of the value which implies that its width would change... but I need to know its "preferred" width after the value of the Date Picker gets changed.

I am interested in knowing this because I am laying out the UIKit widgets using a custom algorithm, and it must know the width of the date picker. The date picker displays as a shaded rounded rectangle, so this is needed -- I don't think you can just "force" the date picker to another width.

EDIT: UIDatePicker seems to collapse into mm/dd/yyyy format when the width is set small. If that affects the fitting size, I'd like to monitor for the change of the intrinsic size.

A solution using a changed handler to force update of this value would be also welcome.


Solution

  • In the on-change handler of whatever you're hooking up the DatePicker with, do this:

    [datePicker setNeedsLayout];
    [datePicker layoutIfNeeded];
    CGFloat width = [datePicker systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].width;
    

    The first two lines are needed in order for it to be the latest size and not from before the change.

    Reference: https://developer.apple.com/forums/thread/790220