Search code examples
iosobjective-cuitextviewhighlightuipopover

Keep text in UITextView highlighted when the popover is dismissed


I have a UIPopover that shows up a plain view containing a UITextView filled with some text. I have managed to highlight the text. When the popover is dismissed, and re-opened, the highlight disappears. I want to keep the text highlighted even if if the application is closed. Any ideas how to achieve that?
The code i used is the following :

    - (void)highlight {

         NSRange selectedRange = self.textViewAll.selectedRange;

         NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc]
                                                        initWithAttributedString:self.textViewAll.attributedText];

         [attributedString addAttribute:NSForegroundColorAttributeName
                                  value:[UIColor redColor]
                                  range:selectedRange];

       //  [highlightedRange addObject:];
// This is where i tried to save each location and length in a mutable array but didn't work
         [highlightedRangeLocation insertObject:[NSNumber numberWithInteger:selectedRange.location] atIndex:indexOfHighlight];
         [highlightedRangeLength insertObject:[NSNumber numberWithInteger:selectedRange.length] atIndex:indexOfHighlight];

///////////////////////////////////////////////////////////////////////////////
         self.textViewAll.attributedText = attributedString;

         indexOfHighlight ++ ;
    }
    - (void)viewDidLoad {
         UIMenuItem *highlightMenuItem = [[UIMenuItem alloc] initWithTitle:@"Highlight" action:@selector(highlight)];
         [[UIMenuController sharedMenuController] setMenuItems:[NSArray arrayWithObject:highlightMenuItem]];

         float sysVer = [[[UIDevice currentDevice] systemVersion] floatValue];

         if (sysVer >= 8.0) {
              self.textViewAll.layoutManager.allowsNonContiguousLayout = NO;
         }


         }

Could anyone point out how to continue from here?

Edit 1 :

The code that close the popover :

- (IBAction)closeFun:(id)sender {

  //   self.popoverPresentationController set

[self dismissViewControllerAnimated:YES completion:nil];
    // [self dismis]

}

Solution

  • Can't you juste save the Highlighted text range in [NSUserDefaults standardUserDefaults] whenever the popover is dismissed, and retrieve it when the popover reappears ?