Posted at

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

More than 5 years have passed since last update.

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