Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to align image to the left and text to the center on a Xamarin button in iOS?

I want to align my text in the center, but the image on the left. I have tried it with HorizontalAlignment, but it aligns both. How to do it?

like image 667
M_B Avatar asked Nov 22 '25 07:11

M_B


1 Answers

I took the time to actually understand how "insets" work, and wrote my own solution.

Ringotan


[assembly: ExportRenderer(typeof(Button), typeof(RingotanButtonRenderer))]
namespace MyAppNamespace
{
    public class MyButtonRenderer : ButtonRenderer
    {
        public override void LayoutSubviews()
        {
            base.LayoutSubviews();

            // Left-align the image and center the text
            // Taken from https://stackoverflow.com/a/71044012/238419
            if (Element.ContentLayout.Position == Button.ButtonContentLayout.ImagePosition.Left)
            {
                const int imageMargin = 20; // This might need to get multiplied by the screen density, not sure yet.  I'll update this later if it does.
                nfloat imageOffset = Control.ImageView.Frame.Left - imageMargin;
                Control.ImageEdgeInsets = new UIEdgeInsets(0, -imageOffset, 0, imageOffset);

                nfloat imageWidth = Control.ImageView.Frame.Width + imageMargin;
                nfloat textOffset = Control.TitleLabel.Frame.Left - (imageWidth + Control.Frame.Width - Control.TitleLabel.Frame.Width) / 2;
                Control.TitleEdgeInsets = new UIEdgeInsets(0, -textOffset, 0, textOffset);
            }
        }
    }
}

Notes:

  • If you want the text to be centered on the overall button, rather than centered on the available remaining space, set imageWidth = 0
  • If you only want this to apply to some buttons, create a new class that extends Button and set the ExportRenderer to that new class. Then only use that new class where you want the text centered.
  • This only works for left-aligned images, but similar math can be used for the other alignments
  • There seems to be a bug where Xamarin/iOS ignores the inset if you update the button's ImageSource or Text. I haven't been able to find a workaround to this bug yet.
like image 180
BlueRaja - Danny Pflughoeft Avatar answered Nov 23 '25 23:11

BlueRaja - Danny Pflughoeft



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!