UIDatePicker 停止工作 Xamarin IOS14

UIDatePicker stopped working Xamarin IOS14

因为我已经在 mac 上更新到 Xcode 12 和 VS(2019 8.7.8 build 4)并将 Xamarin 更新到最新版本(Xamarin.iOS 14.0.0.0) ,我发现我无法使用 UIDatePicker。

DatePicker

查看文档,https://developer.apple.com/documentation/uikit/uidatepicker我需要设置 Style 和 preferredDatePickerStyle,但这些都不是我可以在 (Xamarin) 代码中设置的属性。

有没有人找到解决这个问题以选择日期的方法?

我已经解决了这个问题:

_datePicker.SetValueForKey(new NSNumber(1), new NSString("preferredDatePickerStyle"));

现在显示正确的选择器

Date Selector

一旦我们设置了preferredDatePickerStylesizeToFit,它就会起作用,示例代码如下。

_datePicker = new UIDatePicker(new CGRect(0, 30, 0, 0));
_datePicker.AutoresizingMask = UIViewAutoresizing.FlexibleRightMargin;
_datePicker.Frame = new CGRect(_datePicker.Frame.Location, new CGSize(300, _datePicker.Frame.Size.Height));
_datePicker.Mode = _datePickerMode;
_datePicker.Date = (NSDate)_defaultDate;
_datePicker.PreferredDatePickerStyle = UIDatePickerStyle.Wheels; //Add this in ios14
_datePicker.SizeToFit(); //Add this in ios14

我最近也遇到了这个有趣的问题。当我们用Xcode12打包时,一切正常,但切换到Xcode12及以上打包日期选择和显示时,就出现异常。

因为iOS13.4 UIDatePicker 有新特性

  • @属性(非原子,读写,赋值)UIDatePickerStyle preferredDatePickerStyle API_AVAILABLE(ios(13.4)) API_UNAVAILABLE(tvos, watchos);

如果想保持原来的风格,可以加上这段代码

   _datePick = [[UIDatePicker alloc] init];
   if (@available(iOS 13.4, *)) {
       _datePick.preferredDatePickerStyle = UIDatePickerStyleWheels;
   }

我基本上将其他答案的所有细节放在 public class CustomDatePickerRenderer : DatePickerRenderer for Xamarin Forms in iOS 的相应实现中(省略了我对 CreateNativeControlOnElementPropertyChanged,以及为简洁起见的自定义方法):

protected override void OnElementChanged(ElementChangedEventArgs<DatePicker> e)
{
    const int iosVersionMajorForDatePickerStyleFeature = 13;
    const int iosVersionMinorForDatePickerStyleFeature = 4;
    base.OnElementChanged(e);

    if (e.OldElement != null || Element == null)
    {
        return;
    }

    //Switch back to the Wheels style for the datePicker (in iOS 14 the default of Automatic uses the Compact style)
    if (UIDevice.CurrentDevice.CheckSystemVersion(iosVersionMajorForDatePickerStyleFeature, iosVersionMinorForDatePickerStyleFeature)
        && Control?.InputView is UIDatePicker datePicker && datePicker.PreferredDatePickerStyle != UIDatePickerStyle.Wheels)
    {
        datePicker.PreferredDatePickerStyle = UIDatePickerStyle.Wheels;
        datePicker.SizeToFit();
    }

    //Do whatever other customization is desired
    //UpdateBorderColor();
    //UpdateBorderWidth();
    //UpdateCornerRadius();
    //UpdatePadding();
}