好的,我已经解决了这个问题。解决方案并不漂亮,更好的选择是“Apple 解决了问题”,但这至少有效。
首先,在你的UIMenuItem动作选择器前加上“ magic_ ”。并且不要做出相应的方法。(如果你能做到这一点,那么你无论如何都不需要这个解决方案)。
我正在构建我的UIMenuItems:
NSArray *buttons = [NSArray arrayWithObjects:@"some", @"random", @"stuff", nil];
NSMutableArray *menuItems = [NSMutableArray array];
for (NSString *buttonText in buttons) {
NSString *sel = [NSString stringWithFormat:@"magic_%@", buttonText];
[menuItems addObject:[[UIMenuItem alloc]
initWithTitle:buttonText
action:NSSelectorFromString(sel)]];
}
[UIMenuController sharedMenuController].menuItems = menuItems;
现在,您的捕获按钮点击消息的类需要添加一些内容。(在我的例子中,这个类是UITextField的一个子类。你的可能是别的东西。)
首先,我们一直想要但不存在的方法:
- (void)tappedMenuItem:(NSString *)buttonText {
NSLog(@"They tapped '%@'", buttonText);
}
然后是使之成为可能的方法:
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender {
NSString *sel = NSStringFromSelector(action);
NSRange match = [sel rangeOfString:@"magic_"];
if (match.location == 0) {
return YES;
}
return NO;
}
- (NSMethodSignature *)methodSignatureForSelector:(SEL)sel {
if ([super methodSignatureForSelector:sel]) {
return [super methodSignatureForSelector:sel];
}
return [super methodSignatureForSelector:@selector(tappedMenuItem:)];
}
- (void)forwardInvocation:(NSInvocation *)invocation {
NSString *sel = NSStringFromSelector([invocation selector]);
NSRange match = [sel rangeOfString:@"magic_"];
if (match.location == 0) {
[self tappedMenuItem:[sel substringFromIndex:6]];
} else {
[super forwardInvocation:invocation];
}
}