UITextView定製彈出選單

Eric君發表於2018-01-03

    需求:UITextView選中文字之後,需要定製一些功能,遮蔽系統的某些功能。

自定義一個UITextView的子類YQTextView #####遮蔽系統選單欄#####

#import "YQTextView.h"

@implementation YQTextView

#pragma mark - 選中文字後是否能夠彈出選單
- (BOOL)canBecameFirstResponder {
    return YES;
}

#pragma mark - 選中文字後的系統選單響應的選項
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender {
    if (action == @selector(copy:)) {
        return YES;
    } else if (action == @selector(selectAll:)) {
        return YES;
    }
    return NO;
}

@end
複製程式碼

#####定製彈出選單欄##### 在有需求的ViewController的viewDidLoad方法中新增如下方法,並增加實現方法(若沒有定義實現方法,那麼這功能選單是不會顯示的)

- (void)viewDidLoad {
    [super viewDidLoad];

    UIMenuItem *menuOneItem = [[UIMenuItem alloc] initWithTitle:@"選單一" action:@selector(oneAction:)];
    UIMenuItem *menuTwoItem = [[UIMenuItem alloc] initWithTitle:@"選單二" action:@selector(twoAction:)];
    [UIMenuController sharedMenuController].menuItems = @[menuOneItem, menuTwoItem];
}
#pragma mark - 選單按鈕的實現方法
- (void)oneAction:(id)sender {
    //對應的功能實現體
}

- (void)twoAction:(id)sender {
    //對應的功能實現體
}

複製程式碼

效果圖如下:

效果圖

相關文章