Reputation: 199
I am deveoping an ebook app for ipad/iphone which loads epub file. I would like to know how to highlight a text with a background color and make notes similar to iBook or Kindle in UIWebView and NOT UIView. I am able to drag select the text by long tapping. But I can only see "copy" option. I would like to add highlight and add note to that menu. How to hightlight the text with a background color?... My document is loaded in UIWebView.
Thank you.
Upvotes: 1
Views: 1944
Reputation: 302
What you need to do is add the note and highlight options to your shared menu. In your viewcontroller viewdidload (or anytime after your view has been added). The following adds two menu items with two selector methods to your menu.
UIMenuItem *customMenuItem1 = [[UIMenuItem alloc] initWithTitle:@"Highlight" action:@selector(doHighlight:)];
UIMenuItem *customMenuItem2 = [[UIMenuItem alloc] initWithTitle:@"Note" action:@selector(doNote:)];
//[myArray addObject:customMenuItem2];
NSMutableArray *myArray = [[NSMutableArray alloc]initWithObjects:customMenuItem1,customMenuItem2, nil ] ;
[UIMenuController sharedMenuController].menuItems = myArray;
You may also want to use a bit of javascript to determine the rect that holds your selection, then overlay a translucent uiview over the text.
So, within your doNote method, load up javascript and run it, see the below javascript for an example of what you may want to do.
NSString *rectString = [webView stringByEvaluatingJavaScriptFromString:rectStringText];
The following will get a rect around the text, though it will inherently be larger than your text: if you've highlighted at char 10 on line 2 through char 50 on line 5, it will return a rect that highlights char 0 line 2 through endline line 5.
function selectEl(x,y){
document.designMode = "on";
var el = document.elementFromPoint(x, y);
var rect = el.getBoundingClientRect();
var vx = rect.left;
var width = rect.right - vx;
var height = rect.bottom - rect.top;
var vy = rect.top;
var range = document.createRange();
range.selectNodeContents(el);
var sel = document.getSelection();
sel.removeAllRanges();
sel.addRange(range);
document.designMode = "off";
rectString = '{{'+vx+','+vy+'},{'+width+','+height+'}}';
}
So, now that you have a rectangle string, you can create a CRect from the string returned and uiview to overlay within your webview. [Note, you will have to figure out how to deal with zooming and saving this data for your next load]
Upvotes: 1