首先我使用的是这个UITextView类
textViewClass.h
@interface textViewClass : UITextView
textViewClass.m
@implementation textViewClass
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
NSMutableArray *items = [[[UIMenuController sharedMenuController] menuItems] mutableCopy];
if (!items) items = [[NSMutableArray alloc] init];
UIMenuItem *menuItem;
menuItem = [[UIMenuItem alloc] initWithTitle:@"Add note" action:@selector(doSomethingHere:)];
[items addObject:menuItem];
[[UIMenuController sharedMenuController] setMenuItems:items];
}
return self;
}
- (void)doSomethingHere:(UITextView *)textView
{
NSLog(@"add note: ");
}
在MainViewController.h中
#import "textViewClass.h"
@interface testViewController : UIViewController <UITextViewDelegate>
@property (strong, nonatomic) IBOutlet textViewClass *myTextView;
在MainViewController.m中
- (void)viewDidLoad
{
[super viewDidLoad];
[self.myTextView setEditable:NO];
[self.myTextView setDelegate:self];
[self.myTextView setText:@"Lorem ipsum dolor sit er elit lamet,
consectetaur cillium adipisicing pecu,
sed do eiusmod tempor incididunt ut labore
et dolore magna aliqua. Ut enim ad minim
veniam, quis nostrud exercitation ullamco
laboris nisi ut aliquip ex ea commodo consequat."];
}
#pragma mark - UITextView Delegate
- (void)textViewDidChangeSelection:(UITextView *)textView
{
NSString *string = [self.myTextView textInRange:textView.selectedTextRange];
NSLog(@"%@", string);
}
我想展示&#39;添加备注&#39;当我在myTextView中选择一些文本并将此选择复制到剪贴板并按我的意愿执行某些操作时。
答案 0 :(得分:3)
您必须在自定义UIResponder
课程中实施此类UITextView
方法。
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender {
if (action == @selector(doSomethingHere:) || action == @selector(copy:)) {
if (self.selectedRange.length > 0) {
return YES;
}
}
return NO;
}
在这里,您使用UIResponderStandardEditActions非正式协议下定义的代码过滤操作。
if (action == @selector(doSomethingHere:) || action == @selector(copy:))
如果您只需要yourAction
,那么
if (action == @selector(doSomethingHere:))
第二次更正:如果您实施此协议
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender {
return YES;
}
默认情况下,您将看到所有可能的命令:通过选择器过滤它或者像这样添加您自己的命令,
UIMenuItem *menuItem;
menuItem = [[UIMenuItem alloc] initWithTitle:@"Add note" action:@selector(doSomethingHere:)];
[items addObject:menuItem];
[[UIMenuController sharedMenuController] setMenuItems:@[menuItem]];
希望它能帮到你......
注意:有关详情,请查看NSHipster