LoginSignup
32
31

More than 5 years have passed since last update.

UITextViewでUIMenuControllerを非表示にする

Last updated at Posted at 2013-08-26

UITextViewの入力値で、Copy機能等を独自に制御したかったので、デフォルトのUIMenuControllerを非表示にします。

流れとしては、

UITextViewのサブクラスを生成 → canPerformAction をオーバーライド

となります。

まずは、UITextViewを継承したサブクラスMyUITextViewを作ります。

MyUITextView.h
//
//    MyUIWebView.h
//

#import <UIKit/UIKit.h>

@interface MyUITextView : UITextView

@end

ヘッダファイルはそのまま

MyUITextView.m
//
//    MyUIWebView.m
//

#import "MyUITextView.h"

@implementation MyUITextView

//canPerformActionをオーバーライド
-(BOOL)canPerformAction:(SEL)action withSender:(id)sender
{
    if ( [UIMenuController sharedMenuController] ) {
        [UIMenuController sharedMenuController].menuVisible = NO;
    }
    return NO;
}

クラスの実装部分で、canPerformActionをオーバーライドします。
上記の例だと、MenuControllerの表示自体を非表示するものです。

後は、MyUITextViewを使いたいクラスで、MyUITextView.hをインポートして終了です。
呼び出し例は以下のとおりです。
ここでは、ファイルを読み込んだ際に、MyUITextViewを生成しています。

HogeController.m
//
//    HogeController.m
//

#import "HogeController.h"
#import "MyUITextView.h"

@interface HogeController ()

@end

@implementation HogeController
- (void)viewDidLoad
{
    [super viewDidLoad];

    CGRect rect = CGRectMake(100, 100, 100, 100);
    MyUITextView *tv = [[MyUITextView alloc] initWithFrame:rect];
    tv.editable = YES;
    tv.text = @"あいうえお\nかきくけこ";
    [self.view addSubview:tv];
}

なお、この例はUITextViewのモノですが、UITextFieldやUIWebViewといったクラスにも使えます。

他の実装例

上記の例は、UIMenuController自体を非表示してしまいましたが、例えば「CopyとPasteだけ禁止したい」といったこともあると思います。そういうときは、

//
//    MyUIWebView.m
//

#import "MyUITextView.h"

@implementation MyUITextView

-(BOOL)canPerformAction:(SEL)action withSender:(id)sender
{
    if ( action == @selector(paste:) ) {
        return NO;
    }
    else if ( action == @selector(copy:) ){
        return NO;
    }

    return [super canPerformAction:action withSender:sender];
}

とすると、UIMenuControllerの機能毎に制御することが可能です。

参考: http://stackoverflow.com/questions/6614465/how-do-you-really-remove-copy-from-uimenucontroller/7944656

32
31
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
32
31