Forum Xamarin Xamarin.Forms

Label Spans with inline Hyperlinks?

Apk07Apk07 Member ✭✭

I have code to process a string that may or may not contain one or more URLs. I put these into a label and add label "Spans" together to make a coherent message with clickable links (if any exist). This works by splitting the entire string on a space, checking each part to see if its a valid URI, then splicing them back together.

The problem is this doesn't account for line breaks or other possible whitespace characters. If a linebreak character comes directly after a URL the linebreak itself will be added into the URL.

I tried to circumvent this by using .Split(null) to split on any whitespace instead of just spaces, but then I can't properly re-assemble the string because I will have effectively removed the linebreaks where I need to keep them.

Here is important chunk:

private void SetFormattedText()
{
    var formattedString = new FormattedString();

    if (!string.IsNullOrEmpty(LinksText))
    {
        var splitText = LinksText.Split(null);

        foreach (string textPart in splitText)
        {
            var span = new Span { Text = $"{textPart} " };

            if (IsUrl(textPart)) //Function to check if valid Uri
            {
                span.TextColor = Color.DeepSkyBlue;
                span.TextDecorations = TextDecorations.Underline;
                span.GestureRecognizers.Add(new TapGestureRecognizer
                {
                    Command = _linkTapGesture,
                    CommandParameter = textPart
                });
            }

            formattedString.Spans.Add(span);
        }
    }

    this.FormattedText = formattedString; //Dump the spans into the label 
}

Answers

  • jezhjezh Member, Xamarin Team Xamurai

    Could you please post more details about this question,e.g. a basic demo, so that we can help you better?

Sign In or Register to comment.