2016-03-03 48 views
1

在UIWebView中選擇文本時,我使用以下代碼在UIMenuController中顯示自定義項目。UIMenuController在第一次後保持重置

//Custom UIMenuController actions for highlighting and commenting 
    UIMenuItem *highlightItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"Highlight", nil) action:@selector(highlightAction:) image:[UIImage imageNamed:@"HighlightIcon"]]; 
    UIMenuItem *commentItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"Comment", nil) action:@selector(createCommentAction:) image:[UIImage imageNamed:@"CommentIcon"]]; 

    [UIMenuController sharedMenuController].menuItems = @[highlightItem, commentItem]; 
    [[UIMenuController sharedMenuController] update]; 

它正常工作,在第一時間和只顯示我有兩個自定義選項,但在那之後只要選擇一些文本,它顯示了第一本機的選擇和項目的下一個頁面上的自定義的。

我想知道如何永久刪除原生選項 - 所有其他問題和示例似乎不適用於iOS 7+。

我也有這個用於啓用菜單:

- (BOOL)canBecomeFirstResponder 
{ 
    return YES; 
} 

- (BOOL)canPerformAction:(SEL)action withSender:(id)sender 
{ 
    if (action == @selector(highlightAction:) || 
     action == @selector(createCommentAction:) || 
     return YES; 
    else if (action == @selector(copy:)) 
    { 
     return NO; 
    } 

    return [super canPerformAction:action withSender:sender]; 
} 

#pragma mark - privates 
- (void)pressme:(id)sender 
{ 
    [[UIMenuController sharedMenuController] setTargetRect:[sender frame] inView:self.view]; 
    [[UIMenuController sharedMenuController] setMenuVisible:YES animated:YES]; 
    [[UIMenuController sharedMenuController] update]; 
} 

回答

0

要禁用默認項,在方法canPerformAction:withSender:而不是調用super canPerformAction,只返回NO。

下面是簡單的例子應該如何成爲一個動作(剛剛試了一下,和它的作品):

// Let say we have textField property outlet 

// Action to display menu 
- (IBAction)showMenu:(id)sender { 
    UIMenuItem *item = [[UIMenuItem alloc] initWithTitle:@"test" action:@selector(test:)]; 
    [UIMenuController sharedMenuController].menuItems = @[item]; 
    [[UIMenuController sharedMenuController] update]; 

    [self.textField becomeFirstResponder]; 
    UIMenuController *theMenu = [UIMenuController sharedMenuController]; 
    [theMenu setTargetRect:self.textField.frame inView:self.textField.superview]; 
    [theMenu setMenuVisible:YES animated:YES]; 
    [[UIMenuController sharedMenuController] update]; 

} 

// Enable only "test:" selector here, disable others 
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender { 
    if (action == @selector(test:)) 
     return YES; 
    return NO; 
} 

enter image description here

+0

奇怪似乎並沒有爲我工作那樣。他們仍然都出現在菜單中第二次我突出顯示的東西 - 複製,共享,定義等... –

+0

我實際上使用這個在UIWebView文本突出顯示...也許這會導致差異? –

+0

我得到了問題。如果我在文本字段中寫入內容並選擇文本,則可以看到默認的菜單項。我如何解決它 - 創建自定義類「TextField:UITextField」,並在此類中重寫'canPerformAction:withSender:' – shpasta

相關問題