How to highlight text like in the image?
Asked Answered
S

4

13

How to highlight the text "cell phone" in the image?

enter image description here

Updated

I want to search text on a page and if found, the text should be highlighted in the way I have shown in the attached image.

Swelter answered 30/5, 2013 at 5:15 Comment(0)
G
17

Output

OutPut Image

This Regular Expressions tutorial has detail on how to search the desired text using regular expression on UITextview and how to highlight it.

Essential Code that is to be used:

- (void)viewDidLoad
{
  [super viewDidLoad];
  [self searchData];
}

1) Following code searches for the required pattern from the data i.e TextView:

 - (void) searchData
{


    NSError *error = NULL;
    NSString *pattern = @"Hello";  // pattern to search thee data either regular expression or word.
    NSString *string = self.textView.text;
    NSRange range = NSMakeRange(0, string.length);
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:&error];
    NSArray *matches = [regex matchesInString:string options:NSMatchingProgress ran     ge:range];
   [self highlightMatches:matches];
}

2) Here we highlight the matches obtained from the result of regular expression matching by making use of CALayer and label:

 - (void)highlightMatches:(NSArray *)matches
 {


      __block NSMutableAttributedString *mutableAttributedString = self.textView.attributedText.mutableCopy;
     [matches enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop)
    {

     if ([obj isKindOfClass:[NSTextCheckingResult class]])
     {
         NSTextCheckingResult *match = (NSTextCheckingResult *)obj;
         CGRect rect = [self frameOfTextRange:match.range inTextView:self.textView];

         /** Shadow */

         CALayer *shadowLayer = [CALayer new];
         shadowLayer.frame = CGRectMake(rect.origin.x, rect.origin.y-4, rect.size.width, rect.size.height);
         shadowLayer.cornerRadius = 5;

         shadowLayer.backgroundColor = [UIColor yellowColor].CGColor;
         shadowLayer.shadowColor = [UIColor blackColor].CGColor;
         shadowLayer.shadowOpacity = 0.6;
         shadowLayer.shadowOffset = CGSizeMake(1,1);
         shadowLayer.shadowRadius = 3;

         /** Label */
         UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(rect.origin.x, rect.origin.y-4, rect.size.width, rect.size.height)];
         lbl.font = [UIFont fontWithName:@"Helvetica" size:12];
         lbl.textColor = [UIColor blackColor];
         [lbl setText:[[mutableAttributedString attributedSubstringFromRange:match.range] string]];
         lbl.backgroundColor = [UIColor clearColor];
         lbl.textAlignment = NSTextAlignmentCenter;
         lbl.layer.cornerRadius = 10;

         /** Add Label and layer*/

         [self.view.layer addSublayer:shadowLayer];
         [self.view addSubview:lbl];  
      }
  }];

  }

Function used to obtain the frame of the matched text in the textView:

- (CGRect)frameOfTextRange:(NSRange)range inTextView:(UITextView *)textView
 {
    UITextPosition *beginning = textView.beginningOfDocument; //Error=: request for member 'beginningOfDocument' in something not a structure or union

    UITextPosition *start = [textView positionFromPosition:beginning offset:range.location];
    UITextPosition *end = [textView positionFromPosition:start offset:range.length];
    UITextRange *textRange = [textView textRangeFromPosition:start toPosition:end];
    CGRect rect = [textView firstRectForRange:textRange];  //Error: Invalid Intializer

    return [textView convertRect:rect fromView:textView.textInputView]; // Error: request for member 'textInputView' in something not a structure or union

 }
Gastrointestinal answered 30/5, 2013 at 5:30 Comment(8)
Could you please help me to get the CGRect from the match String?Swelter
With this method i believe it is not possible to get the CGRect of the matched Strings.Gastrointestinal
yeah I Know but i struggling with that I am not getting proper CGrect in my case origin is not coming proper and length and width is fine.Should I show the code?Swelter
using these two ans i found some but not exact what i what.[#10314189 and [#9127209Swelter
a kind of , but while searching the text giving me frame somewhere else not exactly on that.Swelter
Please send me discussion link? I am able to get that.Swelter
@VinayakKini, I ported your frameOfTextRange:inTextView: to Swift to use it here: https://mcmap.net/q/904523/-border-around-every-word-of-uilabel Thanks for your answer here.Tetracaine
@Tetracaine Thanks for letting me know. good that you ported it to swift can be helpful for many :)Gastrointestinal
I
5

Use NSMutableAttributedString this might work for you.

NSString *myString = @"Hello";
NSMutableAttributedString *aString = [[NSMutableAttributedString alloc] initWithString:myString];
NSRange theRange = NSMakeRange(0,[aString length]);

//Here we are setting foreground and background color to text for highlighting it.

[aString addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"MyriadPro-Bold" size:17.5f] range:theRange];
[aString addAttribute:NSForegroundColorAttributeName value:[UIColor purpleColor] range:theRange];
[aString addAttribute:NSBackgroundColorAttributeName value:[UIColor yellowColor] range:theRange];

//You can change the range depending upon what portion of text you want to highlight.

Isaacs answered 30/5, 2013 at 5:42 Comment(3)
Your code is not Working even crashing though.I have fixed and pass this to a UIlabel but i can not see the change.Please suggest if i did wrong way?Swelter
I think u must have done something like this. UILabel *myLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, 10, 100, 100)]; [myLabel setText:aString]; Instead of that set text as below [myLabel setAttributedText:aString]; Hope it works..Isaacs
Does this code give rounded corner background as shown in OP?Luu
T
2

for this you have to use core Text & for highlight you have to draw the text in drawRect method i.e. change in background color to yellow & increase the font size of text

tutorial on coreText

Tessitura answered 30/5, 2013 at 5:20 Comment(0)
D
2

There is a github repository "HighlightedWebView" that achieves virtually the same effect as you so desire.

enter image description here

Drop-in WebView subclass that adds Safari-style in-page search-result highlighting.

Domenicadomenico answered 12/6, 2013 at 2:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.