当我们在UIWebView中突出显示文本时,通常会出现复制,粘贴,定义等。我如何拦截这个,以便当我选择复制时,我会调用其他方法/做其他事情。这可能吗?
答案 0 :(得分:6)
你可以简单地覆盖-copy:
- (void)copy:(id)sender
{
// Do something else here
return [super copy:sender];
}
编辑以回答您的评论。
定义有点棘手,因为它是私有的。但是,您可以实现自己的方法。使用您想要的项目设置UIMenuController。
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];
然后你实现这些方法。
至于define,它的方式更复杂..首先,你需要通过重写-canPerformAction来检查UIReferenceLibraryController是否有定义: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这里是UIWebView上的一个类别:
- (NSString *)selectedText {
return [self stringByEvaluatingJavaScriptFromString:@"window.getSelection().toString()"];
}
然后你需要实现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];
}
编辑以再次回答您的评论
-rectForSelectedText是UIWebView上的另一个自定义类别。
- (CGRect)rectForSelectedText {
return CGRectFromString([self stringByEvaluatingJavaScriptFromString:@"getRectForSelectedWord()"]);
}
它的作用是调用一个返回你可以使用CGRectFromString()转换的字符串的javascript,它看起来像这样:
function getRectForSelectedWord() {
var selection = window.getSelection();
var range = selection.getRangeAt(0);
var rect = range.getBoundingClientRect();
return "{{" + rect.left + "," + rect.top + "}, {" + rect.width + "," + rect.height + "}}";
}
检查this page以了解如何将javascript注入UIWebView。