使用Xamarin Forms在iOS中修改Picker对话框的字体族
解决方案
步骤1:导入自定义字体到iOS原生项目
- 把你要用的自定义字体文件(.ttf/.otf格式)添加到iOS项目的
Resources目录下,属性设置里把「复制到输出目录」选始终复制,「生成操作」选BundleResource - 打开iOS项目的
Info.plist文件,添加Fonts provided by application节点,把字体文件名(带后缀)加到这个节点的子项中。
步骤2:实现iOS端自定义Picker渲染器
在iOS项目中新建自定义渲染器类,代码参考如下:
using UIKit; using Xamarin.Forms; using Xamarin.Forms.Platform.iOS; // 替换为你自己的Xamarin Forms项目命名空间 [assembly: ExportRenderer(typeof(Picker), typeof(YourNamespace.iOS.CustomPickerRenderer))] namespace YourNamespace.iOS { public class CustomPickerRenderer : PickerRenderer { protected override void OnElementChanged(ElementChangedEventArgs<Picker> e) { base.OnElementChanged(e); if (Control != null && e.NewElement != null) { var pickerView = Control.InputView as UIPickerView; if (pickerView != null) { pickerView.WeakDelegate = new CustomPickerViewDelegate(e.NewElement); } } } private class CustomPickerViewDelegate : UIPickerViewDelegate { private readonly Picker _picker; // 替换为你自己的字体PostScript名称和字号 private readonly UIFont _customFont = UIFont.FromName("MyCustomFont-Regular", 16f); public CustomPickerViewDelegate(Picker picker) { _picker = picker; } public override UIView GetView(UIPickerView pickerView, nint row, nint component, UIView view) { UILabel label = view as UILabel ?? new UILabel(); label.Text = _picker.Items[(int)row]; label.Font = _customFont; label.TextAlignment = UITextAlignment.Center; return label; } [Export("pickerView:attributedTitleForRow:forComponent:")] public NSAttributedString GetAttributedTitle(UIPickerView pickerView, nint row, nint component) { var text = _picker.Items[(int)row]; return new NSAttributedString(text, _customFont, UIColor.Black); } } } }
注意事项
UIFont.FromName的第一个参数要填字体的PostScript名称,不是字体文件名,可在Mac字体册中打开对应字体查看该名称,填错会导致字体加载失败自动回退为系统默认字体。- 如果仅需要给部分Picker修改字体,不要全局替换Picker渲染器,可以先在Forms项目自定义继承自Picker的控件
CustomPicker,再把渲染器的绑定对象改为CustomPicker即可,避免影响项目内其他Picker的默认样式。
内容的提问来源于stack exchange,提问作者Manthiram
相关产品推荐
相关产品推荐

