我有一个应用程序,其中UIScrollView
作为UIView
的子视图添加。我已经将UITextField
和UITextview
作为UIScrollView
的子视图添加。当我点击滚动视图时,我想要隐藏键盘。我该如何做?
我有一个应用程序,其中UIScrollView
作为UIView
的子视图添加。我已经将UITextField
和UITextview
作为UIScrollView
的子视图添加。当我点击滚动视图时,我想要隐藏键盘。我该如何做?
只需添加UITapGestureRecognizer
即可。
- (void)viewDidLoad
{
[super viewDidLoad];
UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTapGestureCaptured:)];
[scr addGestureRecognizer:singleTap];
}
- (void)singleTapGestureCaptured:(UITapGestureRecognizer *)gesture
{
//Get touch point
CGPoint touchPoint=[gesture locationInView:scr];
//Hide keyBoard
[self.view endEditing:YES];
}
scrollView.keyboardDismissMode = UIScrollViewKeyboardDismissModeInteractive;
试试这个,
- (void)viewDidLoad
{
[super viewDidLoad];
UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissKeyboard)];
tapGesture.cancelsTouchesInView = NO;
[scrollView addGestureRecognizer:tapGesture];
[tapGesture release];
}
-(void)dismissKeyboard
{
[txtNotes resignFirstResponder];
[textView resignFirstResponder];
}
当我将手势添加到UIScrollView
的子类中时,我遇到了各种手势在我的视图树中相互干扰的问题,例如能够点击子视图、滚动视图,并在所有情况下使键盘消失。我想出了这个解决方案,可以从UIScrollView
的超类或UIViewController
中设置。
DismissKeyboardTapGesture
类使用ARC,在视图下的任何文本字段中工作,并且不会接管来自按钮等子视图的任何点击。还利用iOS7滚动效果来关闭键盘。
从UISScrollView超类设置:
_dismissKeyboard = [[DismissKeyboardTapGesture alloc] initWithView:self];
或来自UIViewController:
_dismissKeyboard = [[DismissKeyboardTapGesture alloc] initWithView:self.view];
这是类:
@interface DismissKeyboardTapGesture : NSObject <UIGestureRecognizerDelegate>
@end
@implementation DismissKeyboardTapGesture
- (id)initWithView:(UIView *)view
{
self = [super init];
if (self) {
UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTap:)];
singleTap.cancelsTouchesInView = NO;
singleTap.delegate = self;
[view addGestureRecognizer:singleTap];
if ([view respondsToSelector:@selector(setKeyboardDismissMode:)]) {
// Bonus effect to dismiss keyboard by scrolling
((UIScrollView *)view).keyboardDismissMode = UIScrollViewKeyboardDismissModeInteractive;
}
}
return self;
}
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
// Don't stop any existing gestures in our view from working
if (otherGestureRecognizer.view == gestureRecognizer.view) {
return YES;
}
return NO;
}
- (void)singleTap:(UIGestureRecognizer*)gestureRecognizer
{
// Close keyboard for any text edit views that are children of the main view
[gestureRecognizer.view endEditing:YES];
}
@end