How to customize a RadioButton on iOS

Rainer 171 Reputation points
2023-03-03T13:54:12.19+00:00

In my app I would like to make the text in my radio button all capital. I first tried to use the TextTransform="Uppercase", but that didn't work (maybe this is a MAUI bug). I then thought I would use a handler for RadioButton, but I can't figure out how to change the text.

In the following, the view.Content = line won't work because Content only has a getter, not a setter. So, how can I change the content?

Microsoft.Maui.Handlers.RadioButtonHandler.Mapper.AppendToMapping(
	"MyRadioButton",
	(handler, view) => {
		if(view.Content is string text) {
			view.Content = text.ToUpperInvariant();
		}
	}
);

I then tried to go use an effect. With that I can find the UIView for the radio button, but I don't know how to find the text or label in it.

protected override void OnAttached()
{
	var effect = Element.Effects.OfType<UppercaseRoutingEffect>().FirstOrDefault();
	if(effect != null && Control is UIKit.UIView view) {
		... what do I do with the view here?
	}
}
.NET MAUI
.NET MAUI
A Microsoft open-source framework for building native device applications spanning mobile, tablet, and desktop.
2,812 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Rainer 171 Reputation points
    2023-03-03T14:24:47.32+00:00

    I figured out a solution, but it's a bit ugly. I wish that TextTransform just worked out of the box.

    	protected override void OnAttached()
    	{
    		var effect = Element.Effects.OfType<UppercaseRoutingEffect>().FirstOrDefault();
    		if(effect != null && Control is UIKit.UIView view) {
    			foreach(var sub in FindViews(view, v => v is UIKit.UILabel)) {
    				var label = (UIKit.UILabel)sub;
    				label.Text = label.Text?.ToUpperInvariant() ?? label.Text;
    			}
    		}
    	}
    
    	private static IEnumerable<UIKit.UIView> FindViews(UIKit.UIView view, Func<UIKit.UIView, bool> checker)
    	{
    		List<UIKit.UIView> results = new();
    		void RecurseView(UIKit.UIView view)
    		{
    			if(checker(view)) {
    				results.Add(view);
    			}
    
    			foreach(var sub in view.Subviews) {
    				RecurseView(sub);
    			}
    		}
    		RecurseView(view);
    		return results;
    	}
    
    0 comments No comments