Search code examples
c#iphoneobjective-cxamarin.iosmonodevelop

How to use PickerView control in MonoDevelop (iPhone)


Hi, I'm new to iPhone development. I'm working on a PickerView control and I'm facing a problem. How do I bind a PickerView control with a string array. It takes a NSObject as the Datasource property. I have an array of items which I want to bind with this PickerView control but I can't.

I've tried this :

String[] item = {"New York", "Toronto", "California"};

pickView.Datasource = (NSObject) item;

but it's not working. Please can anyone tell me how I bind a string array with a PickerView control. Any help in this regard is greatly appreciated.

Note: any help in Objective C is also accepted.


Solution

  • Things work differently on iOS. To provide data to a picker view, you need to create a class that inherits the UIPickerViewModel class:

    public class PickerModel : UIPickerViewModel
    

    Inside that class, you need to override some methods so that your data will be displayed:

    String[] item = {"New York", "Toronto", "California"};
    public override string GetTitle (UIPickerView picker, int row, int component)
    {
        return item[row];
    }
    
    public override int GetRowsInComponent(UIPickerView picker, int component)
    {
        return item.Length;
    }
    

    You then set a new instance of this class to your picker view's Model property:

    pickerView.Model = new PickerModel();