You can simply override -copy:
- (void)copy:(id)sender {
Change the response to your comment.
Defining a little more difficult, since it is private. However, you can implement your own method. Configure the UIMenuController using the required elements.
UIMenuItem *copyItem = [[UIMenuItem alloc] initWithTitle:@"Copy" action:@selector(myCopy:)]; UIMenuItem *defineItem = [[UIMenuItem alloc] initWithTitle:@"Define" action:@selector(myDefine:)]; [[UIMenuController sharedMenuController] setMenuItems:[NSArray arrayWithObjects:defineItem, copyItem, nil]]; [defineItem release]; [copyItem release];
Then you implement these methods.
As for the definition, it is more complicated. First, you need to check if the UIReferenceLibraryController has a definition by overriding -canPerformAction: withSender:
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender { if (action == @selector(myDefine:)) { // Make sure we are on iOS5.x if (NSClassFromString(@"UIReferenceLibraryViewController")) { return [UIReferenceLibraryViewController dictionaryHasDefinitionForTerm:[webView selectedText]]; } } // Implement other custom actions here return NO; }
-selectedText is a category in a UIWebView:
- (NSString *)selectedText { return [self stringByEvaluatingJavaScriptFromString:@"window.getSelection().toString()"]; }
Then you need to implement myDefine:
- (void)myDefine:(UIMenuController *)menuController { CGRect selectedWordFrame = [webView rectForSelectedText]; UIReferenceLibraryViewController *dict = [[UIReferenceLibraryViewController alloc] initWithTerm:[webView selectedText]]; UIPopoverController *popover = [[UIPopoverController alloc] initWithContentViewController:dict]; [popover presentPopoverFromRect:selectedWordFrame inView:webView permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES]; [popover setDelegate:self]; [dict release]; } - (void)popoverControllerDidDismissPopover:(UIPopoverController *)popoverController { [popoverController release]; }
Edit the answer to answer it again.
-rectForSelectedText is another user category in a UIWebView.
- (CGRect)rectForSelectedText { return CGRectFromString([self stringByEvaluatingJavaScriptFromString:@"getRectForSelectedWord()"]); }
What it does is a javascript call that returns a string that you can convert with CGRectFromString (), looks something like this:
function getRectForSelectedWord() { var selection = window.getSelection(); var range = selection.getRangeAt(0); var rect = range.getBoundingClientRect(); return "{{" + rect.left + "," + rect.top + "}, {" + rect.width + "," + rect.height + "}}"; }
Check this page to learn how to embed javascript in a UIWebView.