Search code examples
c#xamarinxamarin.iosuipickerviewvisual-studio-2022

How to set color and text/font size of picker text?


I use a specific picker setup to mimic the action of a drop down list in Xamarin.iOS. The code is:

    public void ConfigureSelectPicker(UITextField pickerTextField, List<string> theData)
    {
        PickerViewModel MyModel = new PickerViewModel();
        MyModel._pickerSource = theData;
        var picker = new UIPickerView
        {
            Model = MyModel,
            ShowSelectionIndicator = true,
            TintColor = UIColor.Blue
        };
        var screenWidth = UIScreen.MainScreen.Bounds.Width;
        var pickerToolBar = new UIToolbar(new RectangleF(0, 0, (float)screenWidth, 44)) { BarStyle = UIBarStyle.Default, Translucent = true };
        var flexibleSpaceButton = new UIBarButtonItem(UIBarButtonSystemItem.FlexibleSpace);
        var doneButton = new UIBarButtonItem(UIBarButtonSystemItem.Done, (sender, e) => pickerTextField.ResignFirstResponder());
        doneButton.Clicked += (object sender, EventArgs e) =>
        {
            pickerTextField.Text = MyModel.SelectedItem;
        };
        pickerToolBar.SetItems(new[] { flexibleSpaceButton, doneButton }, false);

        pickerTextField.InputView = picker;
        pickerTextField.InputAccessoryView = pickerToolBar;
    }

The theData list contains strings that are truncated in the picker. Is there a way I can change the font size to make them fit and also the text color?


Solution

  • You could override GetView method in your UIPickerViewModel.

    public override UIKit.UIView GetView(UIKit.UIPickerView pickerView, nint row, nint component, UIKit.UIView view)
    {
        
        var pickerLabel = view as UILabel;
        if (pickerLabel == null)
        {
            pickerLabel = new UILabel();
            pickerLabel.Font = UIFont.SystemFontOfSize(5);
            pickerLabel.TextColor = UIColor.Red;
        }
        // you should again give the value to the pickerLabel Text based on the row or component of your picker
        if (component = 0)        
        {
            pickerLabel.Text = names[row];
        }
        else
        {
            pickerLabel.Text = row.ToString()        
        }
    
        return pickerLabel;
    }
    

    For more info, you could refer to Picker control in Xamarin.iOS and sample code: PickerControl.