How to programmatically set the color of Placeholder text of a disabled Entry on iOS

JohnHardmanJohnHardman GBUniversity mod

Can anybody tell me please how to specify the color of the placeholder for an Entry that is disabled on iOS? (Android and UWP are sorted).

I know I can workaround it by placing another View over the top of the Entry, but it would be useful to do it "properly" in a custom Entry renderer.

Answers

  • ColeXColeX Member, Xamarin Team Xamurai
    edited August 2018

    You can implement this by custom renderer.

    [assembly: ExportRenderer(typeof(Entry), typeof(CustomEntryRenderer))]
    namespace FormsApp.iOS
    {
        class CustomEntryRenderer :EntryRenderer
        {
            protected override void OnElementChanged(ElementChangedEventArgs<Entry> e)
            {
                base.OnElementChanged(e);
                if (Control != null)
                {
                   if(Control.Enabled == false)
                    {
                        Control.AttributedPlaceholder = new NSAttributedString(Control.Placeholder, new UIStringAttributes { ForegroundColor = UIColor.Red});
                    }
                }
            }
        }
    }
    
  • JohnHardmanJohnHardman GBUniversity mod
    edited August 2018

    Thanks @ColeX . I already had that AttributedPlaceholder code in place, both in OnElementChanged and in OnElementPropertyChanged. There turned out to be two issues:

    (1) A copy-and-paste error on my part - I was calling the base class in OnElementPropertyChanged after setting the color instead of before.
    (2) Changing IsEnabled to false overrode the placeholder color that I had previously set, so I also needed to set the placeholder color each time IsEnabled changed.

    Too many late night coding sessions I think - simple mistakes and omissions :-(

  • ColeXColeX Member, Xamarin Team Xamurai
    edited August 2018

    When you enable or disable the entry ,OnElementPropertyChanged method can be triggered every time, so we can move the logic into OnElementPropertyChanged .

        protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            base.OnElementPropertyChanged(sender, e);
    
            if (Control != null)
            {
                if (Control.Enabled == false)  //disable status
                {
                    Control.AttributedPlaceholder =
                        new NSAttributedString(Control.Placeholder, new UIStringAttributes { ForegroundColor = UIColor.Red });
                }
                else  ////enable status
                {
                    Control.AttributedPlaceholder =
                        new NSAttributedString(Control.Placeholder, new UIStringAttributes { ForegroundColor = UIColor.Gray });
                }
            }
        }
    
Sign In or Register to comment.