Line spacing label in Xamarin Forms

One of the limitations of the Label control in Xamarin Forms is that it's missing a line spacing property. On one of our most recent Forms projects we needed to specify differing line spacing on some labels so I've put together a few code samples to save you time on how to do this in your iOS and Android renderers.

Forms control

The forms control is as easy as they come, it requires just one property which we've made a double:

public class LineSpacingLabel : Label
{
    public double LineSpacing { get; set; }
}

I've named the control the sanzy LineSpacingLabel.

The real magic happens in the iOS and Android renderers.

iOS renderer

The iOS renderer code looks like:

        var lineSpacingLabel = (LineSpacingLabel)this.Element;
        var paragraphStyle = new NSMutableParagraphStyle()
            {
                LineSpacing = (nfloat)lineSpacingLabel.LineSpacing
            };
        var string = new NSMutableAttributedString(lineSpacingLabel.Text);
        var style = UIStringAttributeKey.ParagraphStyle;
        var range = new NSRange(0, string.Length);

        attrString.AddAttribute(style, paragraphStyle, range);

        this.Control.AttributedText = string;

We need the Text property to be set so I've put this code OnElementPropertyChanged.

Android renderer

The Android renderer code is again pretty straight forward:

    protected LineSpacingLabel LineSpacingLabel { get; private set; }

    protected override void OnElementChanged(ElementChangedEventArgs<Label> e)
    {
        base.OnElementChanged(e);

        if (e.OldElement == null)
        {
            this.LineSpacingLabel = (LineSpacingLabel)this.Element;
        }
        
        var lineSpacing = this.LineSpacingLabel.LineSpacing;

        this.Control.SetLineSpacing(1f, (float)lineSpacing);

        this.UpdateLayout();
    }

This renderer doesn't rely on having the Text property set so we can do all of this in OnElementChanged.

Further reading

A couple of in-depth articles about the importance of getting your line spacing right can be found below: