在Xamarin iOS中的UIPickerView中填充列表

时间:2016-04-15 10:55:09

标签: xamarin xamarin.ios uipickerview

我有一个保存在对象中的列表。我想在Xamarin iOS的UIPickerView中填充相同的列表,但它显示了一个错误的tycasting。

该列表来自网络服务。

提前致谢。

1 个答案:

答案 0 :(得分:2)

你看过Xamarin的样品了吗? 这个one正是您正在寻找的,下面是设置自定义UIPickerView的代码片段。

看起来您需要创建一个UIPickerViewModel子类的Model,here是来自此类的Xamarin的文档

void CreatePicker ()
    {
        //
        // Empty is used, since UIPickerViews have auto-sizing,
        // all that is required is the origin
        //
        myPickerView = new UIPickerView (CGRect.Empty){
            AutoresizingMask = UIViewAutoresizing.FlexibleWidth,
            ShowSelectionIndicator = true,
            Model = new PeopleModel (this),
            BackgroundColor = backgroundColor,
            Hidden = true
        };
        // Now update it:
        myPickerView.Frame = PickerFrameWithSize (myPickerView.SizeThatFits (CGSize.Empty));
        View.AddSubview (myPickerView);
    }

    public class PeopleModel : UIPickerViewModel {
        static string [] names = new string [] {
            "Brian Kernighan",
            "Dennis Ritchie",
            "Ken Thompson",
            "Kirk McKusick",
            "Rob Pike",
            "Dave Presotto",
            "Steve Johnson"
        };

        PickerViewController pvc;
        public PeopleModel (PickerViewController pvc) {
            this.pvc = pvc;
        }

        public override nint GetComponentCount (UIPickerView v)
        {
            return 2;
        }

        public override nint GetRowsInComponent (UIPickerView pickerView, nint component)
        {
            return names.Length;
        }

        public override string GetTitle (UIPickerView picker, nint row, nint component)
        {
            if (component == 0)
                return names [row];
            else
                return row.ToString ();
        }

        public override void Selected (UIPickerView picker, nint row, nint component)
        {
            pvc.label.Text = String.Format ("{0} - {1}",
                            names [picker.SelectedRowInComponent (0)],
                            picker.SelectedRowInComponent (1));
        }

        public override nfloat GetComponentWidth (UIPickerView picker, nint component)
        {
            if (component == 0)
                return 240f;
            else
                return 40f;
        }

        public override nfloat GetRowHeight (UIPickerView picker, nint component)
        {
            return 40f;
        }
    }