How do I add a custom UIMenuItem to the UIMenuController in a UITextView?

前端 未结 2 627
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-24 14:26

I\'m trying to add a menu item next to the \"copy\", \"paste\" items in a UITextView. I\'ve created a subclass of UITextView and copied the example from apple\'s docs here:

2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-24 14:55

    So I ended up using the following with results that I wanted, I placed the following block in the viewDidLoad method of my view controller as Alex hinted to:

    - (void)viewDidLoad {
        [super viewDidLoad];
    
        UIMenuItem *menuItem = [[UIMenuItem alloc] initWithTitle:@"Change Color" action:@selector(changeColor:)];
        [[UIMenuController sharedMenuController] setMenuItems:[NSArray arrayWithObject:menuItem]];
        [menuItem release]; 
    }
    

    Then I added the following to the view controller to show the item conditionally when text is selected within the UITextView which I named "textView":

    - (BOOL)canPerformAction:(SEL)action withSender:(id)sender {
        if (action == @selector(changeColor:)) {
            if (textView.selectedRange.length > 0) {
                return YES;
            }
        }
        return NO;
    }
    

    I chose to place the canPerformAction:withSender: method in the view controller instead of a custom UITextView class because this way the other options (e.g. copy, cut, paste, etc.) behave as they normally would since the method is called on every object up the responder chain.

提交回复
热议问题