1
votes

In the product I am building for Mac OSX,I need to support 10.5,10.6 and 10.7. I am using NSTextView as an editor. I use it to display both text and images. I have a requirement about highlighting. This has to work exactly like MS Word. In MS Word you can select a range and change it to yellow color.

I did the same using setMarkedTextAttributes: but that did not work for inline images. So I tried using the LayoutManager and setting the background color but it does not seem to be working either.

And additional point about highlighting is the toggle, so if I select the same range of text and highlight it again, it should get unhighlighted. SO for doing this I am storing all the NSRange in a list and checking if it has been highlighted or not. I feel I am doing something wrong. So I be trying to get the NSRect and then apply the color may be ?.

1

1 Answers

3
votes

Set the background color for that range in the NSAttributedString:

NSMutableAttributedString *mattrstg = [textView textStorage];
[mattrstg addAttribute:NSBackgroundColorAttributeName value:colorHighlighter range:range];

And the existing attributes would be your record of what is and isn't already highlighted. So, to toggle the highlight you could do

[mattrstg enumerateAttribute:NSBackgroundColorAttributeName 
          inRange:rangeToChange 
          options:0 usingBlock:^(id value, NSRange range, BOOL *stop) { 
              if (value) {
                  [mattrstg removeAttribute:NSBackgroundColorAttributeName range:range]; 
              } else {
                  [mattrstg addAttribute:NSBackgroundColorAttributeName value:colorHighlighter range:range]; 
              }
          }];