Search code examples
xamarincolorsstylescustomizationpicker

How to change colors/style of picker popup box in Xamarin (running app on iOS)


So I am coding in Visual Studio and I added a picker in my xaml file. Everything is set up and working fine. I was even able to change the text, title, background, etc colors of the picker itself...

but when you click on the picker, there is this box that pops up with the items to select... How do you access those colors/styles to change them?

My whole app looks custom but that little picker box looks default. (blue button light grey background and gray text)

I'm running the app on iOS simulator btw.

Please help. Thanks


Solution

  • You need a custom renderer to change the item and button style.

    Here is an example:

    [assembly:ExportRenderer(typeof(Picker), typeof(MyiOSPicker))]
    namespace App493.iOS
    {
        public class MyiOSPicker : PickerRenderer, IUIPickerViewDelegate
        {
            IElementController ElementController => Element as IElementController;
    
            public MyiOSPicker()
            {
    
            }
    
            [Export("pickerView:viewForRow:forComponent:reusingView:")]
            public UIView GetView(UIPickerView pickerView, nint row, nint component, UIView view)
            {
    
                UILabel label = new UILabel
                {
                    //here you can set the style of item!!!
    
                    TextColor = UIColor.Red,
                    Text = Element.Items[(int)row].ToString(),
                    TextAlignment = UITextAlignment.Center,
    
                };
                return label;
            }
    
    
            protected override void OnElementChanged(ElementChangedEventArgs<Picker> e)
            {
                base.OnElementChanged(e);
    
                if (Control != null)
                {
                    UIPickerView pickerView = (UIPickerView)Control.InputView;
                    pickerView.WeakDelegate = this;
                    pickerView.BackgroundColor = UIColor.Yellow; //set the background color of pickerview
    
                    //To custom the done button
                    var toolBar = (UIToolbar)Control.InputAccessoryView;
                    var doneButton = toolBar.Items[1];
    
                    UITextAttributes att = new UITextAttributes
                    {
                        Font = UIFont.SystemFontOfSize(20.0f, UIFontWeight.Bold),
                        TextColor = UIColor.Green
                    };
    
                    doneButton.SetTitleTextAttributes(att, UIControlState.Normal);
                }
    
            }
        }
    }
    

    Here is the result:

    enter image description here