UITextView text selection and highlighting in iOS 8

I use UIMenuItem and UIMenuController to add selection to a UITextView so that the user can change the background color of the selected text, as shown in the figures below:

  • Installed text in a UITextView with the highlight function available to the user:

Setected text in <code> UITextView </code>

  • Selected text in a UITextView with a new background color selected by the user after clicking on highlight : Highlighted text in <code> UITextView </code> with a new background color

In iOS 7 , the following code is ideal for this task. :

 - (void)viewDidLoad { [super viewDidLoad]; UIMenuItem *highlightMenuItem = [[UIMenuItem alloc] initWithTitle:@"Highlight" action:@selector(highlight)]; [[UIMenuController sharedMenuController] setMenuItems:[NSArray arrayWithObject:highlightMenuItem]]; } - (void)highlight { NSRange selectedTextRange = self.textView.selectedRange; [attributedString addAttribute:NSBackgroundColorAttributeName value:[UIColor redColor] range:selectedTextRange]; // iOS 7 fix, NOT working in iOS 8 self.textView.scrollEnabled = NO; self.textView.attributedText = attributedString; self.textView.scrollEnabled = YES; } 

But in iOS 8 , text selection jumps over. When I use the select function from UIMenuItem and UIMenuController , it also jumps to another UITextView offset.

How to solve this problem in iOS 8 ?

+3
source share
2 answers

In the end, I decided to solve this problem, and if someone has an even more elegant solution, let me know:

 - (void)viewDidLoad { [super 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.textView.layoutManager.allowsNonContiguousLayout = NO; } } - (void)highlight { NSRange selectedTextRange = self.textView.selectedRange; [attributedString addAttribute:NSBackgroundColorAttributeName value:[UIColor redColor] range:selectedTextRange]; float sysVer = [[[UIDevice currentDevice] systemVersion] floatValue]; if (sysVer < 8.0) { // iOS 7 fix self.textView.scrollEnabled = NO; self.textView.attributedText = attributedString; self.textView.scrollEnabled = YES; } else { self.textView.attributedText = attributedString; } } 
+7
source

move self.textView.scrollEnabled = NO; to the first line of the allocation method.

Hope this helps!

0
source

All Articles