126
125

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

iPhoneキーボードの外をタップしてキーボードを閉じる方法

Last updated at Posted at 2012-12-26

テキストフィールドがあるビューでよくやるパターンです。

キーボードを閉じるためのシングルタップジェスチャを用意

@interface HogeVC ()
@property(nonatomic, strong) UITapGestureRecognizer *singleTap;
@end

ビューの初期化時にジェスチャをself.viewに登録

-(void) viewDidLoad {
	[super viewDidLoad];

	self.singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onSingleTap:)];
	self.singleTap.delegate = self;
	self.singleTap.numberOfTapsRequired = 1;
	[self.view addGestureRecognizer:self.singleTap];
}

ビューコントローラにUIGestureRecognizerDelegateを実装

@interface HogeVC : UIViewController
<UITextFieldDelegate, UIGestureRecognizerDelegate>
@end

シングルタップされたらresignFirstResponderでキーボードを閉じる。

-(void)onSingleTap:(UITapGestureRecognizer *)recognizer {
	[self.textField resignFirstResponder];
}

キーボードを表示していない時は、他のジェスチャに影響を与えないように無効化しておく。

-(BOOL) gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
	if (gestureRecognizer == self.singleTap) {
		// キーボード表示中のみ有効
		if (self.textField.isFirstResponder) {
			return YES;
		} else {
			return NO;
		}
	}
	return YES;
}
126
125
1

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
126
125

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?