13
Help us understand the problem. What are the problem?

More than 5 years have passed since last update.

posted at

iOSの標準キーボード上のジェスチャーを認識する方法

拙作のArrow Noteではキーボード上のジェスチャーを認識して利用しています。これをプライベートメソッドなどを使わずに実現する方法を開示致します。ただし、UIViewの階層を辿ることは非推奨なので、自己責任でお願いします。
以下ではプロパティのtextViewとgestureRecognizerはInterface Builderによって設定されるものとします。

Objective-C
@interface ViewController : UIViewController
@property IBOutlet UITextView *textView;
@property IBOutlet UIGestureRecognizer *gestureRecognizer;
@end

@implementation ViewController
-(void) viewDidLoad
{
    self.textView.inputAccessoryView
        = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 1)];
}

-(void) viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter]
         addObserver:self
            selector:@selector(keyboardDidShow:)
                name:UIKeyboardDidShowNotification
              object:nil];
    [[NSNotificationCenter defaultCenter]
         addObserver:self
            selector:@selector(keyboardWillHide:)
                name:UIKeyboardWillHideNotification
              object:nil];
}

-(void) viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter]
         removeObserver:self
                   name:UIKeyboardDidShowNotification
                 object:nil];
    [[NSNotificationCenter defaultCenter]
         removeObserver:self
                   name:UIKeyboardWillHideNotification
                 object:nil];
}

-(void) keyboardDidShow:(NSNotification*)notif
{
    [self.textView.inputAccessoryView.superview
        addGestureRecognizer:self.gestureRecognizer];
}

- (void)keyboardWillHide:(NSNotification*)notif
{
    [self.textView.inputAccessoryView.superview
        removeGestureRecognizer:self.gestureRecognizer];
}

@end
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Sign upLogin
13
Help us understand the problem. What are the problem?