我有一个UIScrollView
添加为子视图的应用程序UIView
。我已经添加了UITextField
,UITextview
作为UIScrollView
.I 的子视图。当我在滚动视图中点击时,我想关闭键盘。我怎样才能做到这一点?
问问题
3665 次
4 回答
10
只需添加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];
}
于 2013-02-09T13:06:44.380 回答
2
在 iOS 7 中,您可以轻松实现这一点。
scrollView.keyboardDismissMode = UIScrollViewKeyboardDismissModeInteractive;
于 2014-02-11T16:34:32.723 回答
0
试试这个,
- (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];
}
于 2013-02-09T05:50:21.350 回答
0
当我将手势添加到 的子类时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
于 2013-11-01T19:59:26.710 回答