Search code examples
c#iosxamarinuipickerview

uipickerview with three columns - xamarin c#


I want a UIPickerView with three columns but is not working. I can not find the error, can someone help please. Below is the code:

enter image description here

static string[] nomesPeso = new string[]
{
    "Back Squat",
    "Front Squat",
    "OHS - Overhead Squat"
};

static string[] nomesUnidades = new string[]
{
    "Reps",
    "Kgs",
    "Lbs",
    "Metros"
};

static string[] nomesRepeticoes = new string[]
{
    "1 RM",
    "2 RM",
    "3 RM"
};

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

public override nint GetRowsInComponent(UIPickerView pickerView, nint component)
{
    switch (component)
    {
        case 0:
            return nomesPeso.Length;
        case 1:
            return nomesRepeticoes.Length; 
        case 2:
            return nomesUnidades.Length;
        default:
            throw new NotImplementedException();
    }
}

public override string GetTitle(UIPickerView picker, nint row, nint component)
{
    switch (component)
    {
        case 0:
            return nomesPeso[row];
        case 1:
            return nomesRepeticoes[row]; 
        case 2:
            return nomesUnidades[row];
        default:
            throw new NotImplementedException();
    }
}

Solution

  • You can adjust the column width by overriding GetComponentWidth of the UIPickerViewDelegate:

    class MyPickerViewDelegate : UIPickerViewDelegate
    {
        public override nfloat GetComponentWidth(UIPickerView pickerView, nint component)
        {
            // equal size for every column
            return pickerView.Frame.Width/3;
        }
    }
    

    and then set it on your UIPickerView

    myPickerView.Delegate = new MyPickerViewDelegate();
    

    This code distributes the columns equal. You can of course return a custom width for every column by using the component parameter.