LoginSignup
12
13

More than 5 years have passed since last update.

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

Posted at

拙作の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
12
13
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
12
13