iPhone Development: Grabbing selected/highlighted text on UIWebView

本秂侑毒 提交于 2019-11-29 09:28:58

问题


Greetings,

Please kindly advice on how possibly I can get the selected text on UIWebVIew.

I went on to search on how to deal with selected/highlighted text and found the following:

Selection and Menu Management

To copy or cut something in a view, that “something” must be selected. It can be a range of text, an image, a URL, a color, or any other representation of data, including custom objects. To implement copy-and-paste behavior in your custom view, you must manage the selection of objects in that view yourself. If the user selects an object in the view by making a certain touch gesture (for example, a double-tap) you must handle that event, internally record the selection (and deselect any previous selection), and perhaps visually indicate the new selection in the view. If it is possible for users to select multiple objects in your view for copy-cut-paste operations, you must implement that multiple-selection behavior.

And that's where I got lost. "...record the selection" - I'm not even sure how to represent a selection let alone recording it.

Any help is very much appreciated. ^^ Cheers!

Kind regards, oonoo


回答1:


You can use stringByEvaulatingJavaScriptFromString to get the currently selected text in a UIWebView.

NSString *selection = [self.webView stringByEvaluatingJavaScriptFromString:@"window.getSelection().toString()"];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Selected Text" message:selection delegate:nil cancelButtonTitle:@"Okay" otherButtonTitles:nil];
[alert show];
[alert release], alert = nil;



回答2:


Take a look at using window.getSelection() in JavaScript. It will allow you to get the current text selection which you could then store in a global variable and access that variable via the stringByEvaluatingJavaScriptFromString method on UIWebView. Unfortunately, I don't know of a way in iOS JavaScript to identify when the text selection has changed so instead use an interval to continuously check for that. I have actually done all this so I know it can work. In terms of storing the text selection ranges for later use as well as applying styles I would look into a JavaScript library named rangy. I found it to be incredibly useful in creating highlighting jQuery plugin (that works on both the desktop and on iOS - not for Android though).



来源:https://stackoverflow.com/questions/1968872/iphone-development-grabbing-selected-highlighted-text-on-uiwebview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!