I wanted to add/test the new effects feature to a Xamarin.Forms button, but got a problem with not being able to remove the white highlight effect on iOS.
[assembly: Xamarin.Forms.ResolutionGroupName("Effects")] [assembly: Xamarin.Forms.ExportEffect(typeof(Page3Effect), "Page3Effect")] namespace ButtonTests.iOS { public class Page3Effect : Xamarin.Forms.Platform.iOS.PlatformEffect { protected override void OnAttached() { var button = (UIButton)Control; //var element = (Xamarin.Forms.Button)Element; //var container = (Xamarin.Forms.Platform.iOS.ButtonRenderer)Container; button.SetBackgroundImage(UIImage.FromFile("button_normal.png"), UIControlState.Normal); button.SetBackgroundImage(UIImage.FromFile("button_pressed.png"), UIControlState.Highlighted); } protected override void OnDetached() { // Use this method if you wish to reset the control to original state } } }
The problem here is that i UIButton is of type RoundedRect, and this is not changeable after the construction.
After reading the sourcecode for Xamarin.Forms, I found this:
protected override void OnElementChanged(ElementChangedEventArgs<Button> e) { base.OnElementChanged(e); if (e.NewElement != null) { if (Control == null) { SetNativeControl(new UIButton(UIButtonType.RoundedRect)); Debug.Assert(Control != null, "Control != null"); _buttonTextColorDefaultNormal = Control.TitleColor(UIControlState.Normal); _buttonTextColorDefaultHighlighted = Control.TitleColor(UIControlState.Highlighted); _buttonTextColorDefaultDisabled = Control.TitleColor(UIControlState.Disabled); Control.TouchUpInside += OnButtonTouchUpInside; } UpdateText(); UpdateFont(); UpdateBorder(); UpdateImage(); UpdateTextColor(); } }
The problem was the SetNativeControl(new UIButton(UIButtonType.RoundedRect));
It was then easy to figure out that I could make some code like this to fix it:
(seems to work)
[assembly: ExportRenderer(typeof(CustomButton), typeof(CustomButtonRenderer))] namespace ButtonTests.iOS { public class CustomButtonRenderer : ButtonRenderer { protected override void OnElementChanged(ElementChangedEventArgs<Button> e) { SetNativeControl(new UIButton(UIButtonType.Custom)); Control.TouchUpInside += (sender, ev) => Element?.Command?.Execute(null); if (Element.TextColor == Color.Default) //#00000000 Element.TextColor = Control.TitleColor(UIControlState.Normal).ToColor(); //#FFFFFFFF base.OnElementChanged(e); } } }
So thanks for opensourcing Xamarin forms.
And maybe it is possible to a way to set the UIButtonType in the future (could not figure out another way now).