Search code examples
c#xamarin.iosuipickerviewuiactionsheet

Why does my UIPickerView crashing when selecting


I have created a sample on github Github link

When clicking on a row or trying to scroll in the UIPickerView it will crash and i wonder why.

// create a ActionSheet
var actionPickerSheet = new UIActionSheet("Select a Category");
actionPickerSheet.Style = UIActionSheetStyle.BlackTranslucent;
// Create UIpickerView
var catPicker = new UIPickerView(){
    Model = new catPickerModel(),
    AutosizesSubviews = true,
    Hidden = false,
    ShowSelectionIndicator = true
};
// show inside view and add the catPicker as subView
actionPickerSheet.ShowInView(View);
actionPickerSheet.AddSubview(catPicker);
// resize both views so it fits smoothly
actionPickerSheet.Frame = new RectangleF(0,100,320,500);
catPicker.Frame = new RectangleF(actionPickerSheet.Frame.X,actionPickerSheet.Frame.Y-25,actionPickerSheet.Frame.Width, 216);

And the Model

private class catPickerModel : UIPickerViewModel
{
    public string[] protocolNames = new string[]
    {
        "Web", "Phone Call", "Google Maps", "SMS", "Email"
    };

    public override int GetComponentCount(UIPickerView uipv)
    {
        return 1;
    }

    public override int GetRowsInComponent( UIPickerView uipv, int comp)
    {
        //each component has its own count.
        int rows = protocolNames.Length;
        return(rows);
    }

    public override string GetTitle(UIPickerView uipv, int row, int comp)
    {  
        //each component would get its own title.
        return protocolNames[row];
    }

    public override void Selected(UIPickerView uipv, int row, int comp)
    {
        Console.WriteLine("selected:" + row);
    }

    public override float GetComponentWidth(UIPickerView uipv, int comp)
    {
        return 300f;
    }
}

I have no idea why it keeps crashing, is it some method i am missing in the Model or am i trying to do this in the wrong way ?

Thanks


Solution

  • Try to make your catPicker to a private variable of the class:

    namespace TextfieldUIPickerView
    {
        public partial class TextfieldUIPickerViewViewController : UIViewController
        {
            private UIPickerView catPicker;
     ...
    

    Looks like the GC has collected your catPicker and disposed it.