UIMenuController的示例
UIMenuController須知
- 默認(rèn)情況下, 有以下控件已經(jīng)支持UIMenuController
- UITextField
- UITextView
- UIWebView
讓其他控件也支持UIMenuController(比如UILabel)
- 自定義UILabel
- 重寫2個(gè)方法
/**
* 讓label有資格成為第一響應(yīng)者
*/
- (BOOL)canBecomeFirstResponder
{
return YES;
}
/**
* label能執(zhí)行哪些操作(比如copy, paste等等)
* @return YES:支持這種操作
*/
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender
{
if (action == @selector(cut:) || action == @selector(copy:) || action == @selector(paste:)) return YES;
return NO;
}
- 實(shí)現(xiàn)各種操作方法
- (void)cut:(UIMenuController *)menu
{
// 將自己的文字復(fù)制到粘貼板
[self copy:menu];
// 清空文字
self.text = nil;
}
- (void)copy:(UIMenuController *)menu
{
// 將自己的文字復(fù)制到粘貼板
UIPasteboard *board = [UIPasteboard generalPasteboard];
board.string = self.text;
}
- (void)paste:(UIMenuController *)menu
{
// 將粘貼板的文字 復(fù)制 到自己身上
UIPasteboard *board = [UIPasteboard generalPasteboard];
self.text = board.string;
}
- 讓label成為第一響應(yīng)者
// 這里的self是label
[self becomeFirstResponder];
- 顯示UIMenuController
UIMenuController *menu = [UIMenuController sharedMenuController];
// targetRect: MenuController需要指向的矩形框
// targetView: targetRect會(huì)以targetView的左上角為坐標(biāo)原點(diǎn)
[menu setTargetRect:self.bounds inView:self];
// [menu setTargetRect:self.frame inView:self.superview];
[menu setMenuVisible:YES animated:YES];
自定義UIMenuController內(nèi)部的Item
- 添加item
// 添加MenuItem(點(diǎn)擊item, 默認(rèn)會(huì)調(diào)用控制器的方法)
UIMenuItem *ding = [[UIMenuItem alloc] initWithTitle:@"頂" action:@selector(ding:)];
UIMenuItem *replay = [[UIMenuItem alloc] initWithTitle:@"回復(fù)" action:@selector(replay:)];
UIMenuItem *report = [[UIMenuItem alloc] initWithTitle:@"舉報(bào)" action:@selector(report:)];
menu.menuItems = @[ding, replay, report];
說明:MJ大神的筆記