public static void HighlightText(this UILabel textView, string searchText, UIColor foregroundColor, UIColor backgroundColor = null) { var highlightMarker = new HighlightMarker(textView.Text, searchText); var textAttributed = new NSMutableAttributedString(textView.Text); foreach (var segment in highlightMarker) { int fromIndex = segment.FromIndex; int length = segment.Length; bool isHighlighted = segment.IsHighlighted; if (isHighlighted) { var colourAttribute = new UIStringAttributes { ForegroundColor = foregroundColor, BackgroundColor = backgroundColor }; textAttributed.SetAttributes(colourAttribute, new NSRange(fromIndex, length)); } } textView.AttributedText = textAttributed; }
private static void OnTextChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e) { var textBlock = d as TextBlock; if (textBlock == null) { return; } string fulltext = GetFullText(textBlock) ?? string.Empty; string highlightedText = GetHighlightedText(textBlock) ?? string.Empty; textBlock.Inlines.Clear(); if (string.IsNullOrEmpty(fulltext) || string.IsNullOrEmpty(highlightedText)) { textBlock.Inlines.Add(new Run { Text = fulltext }); return; } var foregroundBrush = GetForeground(textBlock) ?? ColorHelper.GetDefaultForegroundBrush(); #if !(WINDOWS_APP || WINDOWS_PHONE || WINDOWS_PHONE_APP || WINDOWS_UWP) var backgroundBrush = GetBackground(textBlock) ?? ColorHelper.GetDefaultBackgroundBrush(); #endif var highlightProcessor = GetHighlightProcessor(textBlock); var highlightMarker = new HighlightMarker(fulltext, highlightedText, highlightProcessor); foreach (var current in highlightMarker) { int fromIndex = current.FromIndex; int length = current.Length; bool isHighlighted = current.IsHighlighted; var inlineRun = new Run { Text = fulltext.Substring(fromIndex, length) }; if (isHighlighted) { inlineRun.Foreground = foregroundBrush; #if !(WINDOWS_APP || WINDOWS_PHONE || WINDOWS_PHONE_APP || WINDOWS_UWP) inlineRun.Background = backgroundBrush; #endif } textBlock.Inlines.Add(inlineRun); } }
public static void HighlightText(this TextView textView, string searchText, Color foregroundColor, Color?backgroundColor = null) { var highlightMarker = new HighlightMarker(textView.Text, searchText); var spannableStringBuilder = new SpannableStringBuilder(textView.Text); foreach (var current in highlightMarker) { int fromIndex = current.FromIndex; int endIndex = fromIndex + current.Length; bool isHighlighted = current.IsHighlighted; if (isHighlighted) { spannableStringBuilder.SetSpan(new ForegroundColorSpan(foregroundColor), fromIndex, endIndex, SpanTypes.ExclusiveExclusive); if (backgroundColor.HasValue) { spannableStringBuilder.SetSpan(new BackgroundColorSpan(backgroundColor.Value), fromIndex, endIndex, SpanTypes.ExclusiveExclusive); } } } textView.TextFormatted = spannableStringBuilder; }