How does one know the fitting width of a UIDatePicker in a selector hooked up with UIControlEventValueChanged? By fitting width, I mean the width of the grey background rounded box displayed with the date -- I need to get the width of that whenever the date is changed.
How does one know the fitting width of a UIDatePicker in a function hooked up with UIControlEventValueChanged
Couldn't you just use the systemLayoutSizeFitting
method in the value-changed selector?
datePicker.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize).width
@BabyJ Nope, somehow it does not return the correct preferred width after change.
Okay, I think I figured it out. What I didn't realise before when testing systemLayoutSizeFitting
was that the width being printed was actually the old width, not the updated one. Just to confirm, I wrapped the print statement in a Task
(or you could do a tiny delay), and now it prints the correct width after the change.
Waiting for a tiny delay is bad since we have no idea about the clients' phone speed AND there's a delay.
How would you do a task in objc?
The main point I'm trying to get across is that you would need to wait for the next layout pass after the call to valueChanged
so that the new width is the correct one. So, it's however you would do that normally — either by:
1. Waiting for the next update (I'd assume the equivalent to Task
would be using GCD, like Swift used to have DispatchQueue.main.async
):
dispatch_async(dispatch_get_main_queue(), ^{
CGFloat width = [datePicker systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].width;
});
2. Forcing a layout update so the width is updated immediately:
[datePicker setNeedsLayout];
[datePicker layoutIfNeeded];
CGFloat width = [datePicker systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].width;
3. Another method you prefer using.
Hope I've explained it better and this solves your issue.