A simple UIPickerView in MonoTouch (Xamarin)?

P. Sami picture P. Sami · Mar 22, 2013 · Viewed 23.9k times · Source

Can anybody describe how I can create a UIPickerView in monotouch using XCode and populate it with sample data?

I did look at the example here: https://github.com/xamarin/monotouch-samples/blob/master/MonoCatalog-MonoDevelop/PickerViewController.xib.cs but this hasn't been very helpful since I am creating my UIPickerView in the XCode. Here's what I have so far:

public partial class StatusPickerPopoverView : UIViewController
{
    public StatusPickerPopoverView (IntPtr handle) : base (handle)
    {
        pickerStatus = new UIPickerView();
        pickerStatus.Model = new StatusPickerViewModel();
    }

    public StatusPickerPopoverView (): base ()
    {
    }

    public class StatusPickerViewModel : UIPickerViewModel
    {
        public override int GetComponentCount (UIPickerView picker)
        {
            return 1;
        }

        public override int GetRowsInComponent (UIPickerView picker, int component)
        {
            return 5;
        }

        public override string GetTitle (UIPickerView picker, int row, int component)
        {

            return "Component " + row.ToString();
        }
    }
}

Answer

P. Sami picture P. Sami · Mar 25, 2013

So I basically found the answer and it was waaaaaaaaaaaaaaay easier than you can think!

The model has to be set in ViewDidLoad otherwise will crash... That's why it was not being populated correctly. Remember: set it up in "ViewDidLoad".

public partial class StatusPickerPopoverView : UIViewController
{
    public StatusPickerPopoverView (IntPtr handle) : base (handle)
    {
    }

    public override ViewDidLoad()
    {
        base.ViewDidLoad();

        pickerStatus = new UIPickerView();
        pickerStatus.Model = new StatusPickerViewModel();
    }

    public class StatusPickerViewModel : UIPickerViewModel
    {
        public override int GetComponentCount (UIPickerView picker)
        {
            return 1;
        }

        public override int GetRowsInComponent (UIPickerView picker, int component)
        {
            return 5;
        }

        public override string GetTitle (UIPickerView picker, int row, int component)
        {

            return "Component " + row.ToString();
        }
    }
}