DataPicker for iOS & Android

Xamarin.Forms 的 Picker 控件是通过点击一个文本框,然后打开一个弹出框, 把"简单"数据列出来. 注意只限制于简单数据!! 无法绑定高级数据源,无法修改控件的文本颜色/大小 !

XFControls 为了解决这个问题, 自定义了一个控件: DataPicker, 该控件的优点

  • 直接展示到界面上的!!
  • 支持复杂数据源
  • 可以更改文本大小/颜色,甚至分隔线的颜色!
  • 天生的联动(省市县选择等)

先看一下效果图:

ios.png
android.png

原理其实很简单

iOS 下就是一个 UIPickerView, 外加一个 UIPickerViewModel 做为数据源承载.
Android 下是一个 NumberPicker.

麻烦 1 Android

Android 下的文本颜色/大小的处理有点蛋疼, 本来是从 NumberPicker 派生了一个 ColorNumberPicker , 然后重载 AddView 方法, 在 AddView 方法里判断传入的 view 参数是否是 EditText, 如果是,则更新文本颜色及大小, 但是这个 NumberPicker 居然有一个坑,一个坑:

AddView 优先于构造函数运行!!! 通过构造函数初始化的颜色根本无法应用于子 view 上!

不知道这是 Xamarin 的坑,还是 Android API 的坑!!
这个解决方法是 Android 界的普遍做法, 但是这条路在 Xamarin 上行不通!

还好, 找到了另外一个途径:
通过反射 Child view 来更改

private void UpdateApperance(
     Android.Graphics.Color txtColor,
     float textSize
     ) {
     int count = this.Control.ChildCount;
     for (int i = 0; i < count; i++) {
         var child = this.Control.GetChildAt(i);
         if (child is EditText) {
             try {
                 var fld = this.Control.Class.GetDeclaredField("mSelectorWheelPaint");
                 fld.Accessible = true;
 
 
                 var edt = (EditText)child;
                 edt.SetTextSize(ComplexUnitType.Px, textSize);
                 edt.SetTypeface(edt.Typeface, TypefaceStyle.Normal);
                 edt.SetTextColor(txtColor);
 
                 var paint = (Paint)fld.Get(this.Control);
                 paint.TextSize = TypedValue.ApplyDimension(ComplexUnitType.Px, textSize, this.Control.Resources.DisplayMetrics);
                 paint.Color = txtColor;
                 paint.SetTypeface(edt.Typeface);
             } catch {
 
             }
         }
     }
     this.Control.Invalidate();
 }

修改分隔线的颜色:

private void UpdateDividerColor(Android.Graphics.Color color) {
    try {
        var fld = this.Control.Class.GetDeclaredField("mSelectionDivider");
        fld.Accessible = true;
 
        var d = (Drawable)fld.Get(this.Control);
        d.SetColorFilter(color, PorterDuff.Mode.SrcAtop);
        d.InvalidateSelf();
        this.Control.PostInvalidate(); // Drawable is dirty
 
    } catch (Exception e) {
 
    }
}

麻烦2 iOS

相对 Android 来说,这根本就不是问题

ios 下只需要修改上面所说的 UIPickerViewModel, 重载 GetView 方法( GetView 其实就是 ios API 里的 pickerView:viewForRow:forComponent:reusingView: 方法)

public override UIView GetView(UIPickerView pickerView, nint row, nint component, UIView view)
{
 //var lbl = base.GetView(pickerView, row, component, view);
 var size = pickerView.RowSizeForComponent(component);
 var lbl = new UILabel() {
        Frame = new CoreGraphics.CGRect(0, 0, size.Width, size.Height),
        TextAlignment = UITextAlignment.Center
    };
 
    lbl.Text = Values[(int)row];
    lbl.TextColor = this.TextColor;// this.Element.TextColor.ToUIColor();
    lbl.Font = UIFont.SystemFontOfSize(this.FontSize);
 
 return lbl;
}

注意方法体内的第一句, base.GetView(xxx) ,被注释掉了, 因为这个方法是不能直接在代码里使用的!!!它里面直接抛出个异常出来.

加上这段代码后, 文本的颜色/大小都可以修改了.
但是找了一圈可重载的方法,没有一个是用于修改分隔线颜色的方法.

网上找了一段:

private void UpdateDividerColor(UIPickerView picker, UIColor color) {
    foreach (var v in picker.Subviews) {
        if (v.Frame.Size.Height < 1) {
            v.BackgroundColor = color;
        }
    }
}

这个方法也有个坑:

它只能在上面说的 GetView 方法里调用 ! 放在其它地方, picker.Subviews 无论如何都是空的!!!

如何使用

  • Install-Package XFControls

  • Nuget : Install-Package XFControls

    • iOS Project Please insert the following code before global::Xamarin.Forms.Forms.Init(); at file AppDelegate.cs
    AsNumAssemblyHelper.HoldAssembly();
    
    • Android Project also please insert the following code before Xamarin.Forms.Forms.Init(this, bundle) at file MainActivity.cs;
    AsNumAssemblyHelper.HoldAssembly();
    
* xaml

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="Example.DataPickerExample"
xmlns:ctrls="clr-namespace:AsNum.XFControls;assembly=AsNum.XFControls"
>

<Grid ColumnSpacing="0">
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>

<ctrls:DataPicker Grid.Column="0"
                  ItemsSource="{Binding Datas}"
                  DisplayPath="Name"
                  TextColor="Green"
                  DividerColor="Green"
                  x:Name="d1"
                  />

<ctrls:DataPicker Grid.Column="1"
                  ItemsSource="{Binding Path=SelectedItem.Children, Source={x:Reference d1}}"
                  DisplayPath="Name"
                  TextColor="Blue"
                  DividerColor="Blue"
                  />

</Grid>

</ContentPage>


* cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Xamarin.Forms;

namespace Example {
public partial class DataPickerExample : ContentPage {

    public IEnumerable<DataPickerItem> Datas { get; }
    = new List<DataPickerItem>() {
        new DataPickerItem() { ID = 1, Name= "Asia", Children=new List<DataPickerItem>() { new DataPickerItem() { Name = "China" }, new DataPickerItem() { Name="Japan"}, new DataPickerItem() { Name= "Singapore" } } },
        new DataPickerItem() { ID = 1, Name= "America", Children=new List<DataPickerItem>() { new DataPickerItem() { Name = "USA" }, new DataPickerItem() { Name="Brazil"}, new DataPickerItem() { Name="Canda" } } },
        new DataPickerItem() { ID = 1, Name= "Europe", Children=new List<DataPickerItem>() { new DataPickerItem() { Name = "English" }, new DataPickerItem() { Name="Franch"} , new DataPickerItem() { Name="Germany"} } },
    };

    public DataPickerExample() {
        InitializeComponent();

        this.BindingContext = this;
    }

    public class DataPickerItem {

        public int ID { get; set; }

        public string Name { get; set; }

        public IEnumerable<DataPickerItem> Children {
            get; set;
        }
    }
}

}


## 开源项目地址
XFControls <https://github.com/gruan01/XFControls>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 161,326评论 4 369
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 68,228评论 1 304
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 110,979评论 0 252
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,489评论 0 217
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,894评论 3 294
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,900评论 1 224
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 32,075评论 2 317
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,803评论 0 205
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,565评论 1 249
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,778评论 2 253
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,255评论 1 265
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,582评论 3 261
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,254评论 3 241
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,151评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,952评论 0 201
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 36,035评论 2 285
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,839评论 2 277

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 170,590评论 25 707
  • ¥开启¥ 【iAPP实现进入界面执行逐一显】 〖2017-08-25 15:22:14〗 《//首先开一个线程,因...
    小菜c阅读 6,217评论 0 17
  • 内容抽屉菜单ListViewWebViewSwitchButton按钮点赞按钮进度条TabLayout图标下拉刷新...
    皇小弟阅读 46,427评论 22 663
  • 昨天晚上在值晚自习的时候,班里有一个女生上来给我商量说,明天上午上课她想利用一节课的时间,给大家分享一下她学习英语...
    荷中仙子阅读 193评论 1 1
  • 白孝文的堕落,是一个让我那么憎恨田小娥的原因。在未看到他的“衣锦还乡”之前,我还问了之前看过这部小说的人,白孝文是...
    zhuzhu_302阅读 386评论 0 0