Skip to content

Instantly share code, notes, and snippets.

@wcoder
Last active July 14, 2021 15:32
Show Gist options
  • Save wcoder/04d8cb40de92e1ffe0d11b7c48333805 to your computer and use it in GitHub Desktop.
Save wcoder/04d8cb40de92e1ffe0d11b7c48333805 to your computer and use it in GitHub Desktop.
Xamarin.iOS, Xamarin.Android Highlight mentions in label/textview

Core

public static IEnumerable<(int Start, int Length)> DetectMentions(string text)
{
    var matches = Regex.Matches(text, @"\B@(\w|@|\.)+", RegexOptions.IgnorePatternWhitespace);

    foreach (Match mention in matches)
    {
        yield return (mention.Index, mention.Value.Length);
    }
}

iOS

var text = TextLabel.Text;
var ranges = EmptyClass.DetectMentions(text).Select(range => new NSRange(range.Start, range.Length));

var str = text.BuildAttributedString().HighlightStrings(ranges, UIColor.Red);

TextLabel.AttributedText = str;

Extention method from XToolkit.Common.iOS.Extentions

Android

var tvHelloWorld = (TextView)FindViewById(Resource.Id.textView1);

var str = tvHelloWorld.Text;
var ranges = EmptyClass.DetectMentions(str);

tvHelloWorld.HighlightStrings(ranges, Color.Red);

Extention method:

public static class TextViewExtentions
{
    public static void HighlightStrings(this TextView textView,
        IEnumerable<(int Start, int Length)> ranges,
        Color color)
    {
        var text = textView.Text;
        var spannedString = new SpannableString(text);

        foreach (var (Start, Length) in ranges)
        {
            spannedString.SetSpan(
                    new ForegroundColorSpan(color),
                    Start,
                    Start + Length,
                    SpanTypes.InclusiveInclusive);
        }

        textView.SetText(spannedString, TextView.BufferType.Spannable);
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment