从一个的UITextField驳回键盘,UITextView的UIScrollView的作为一个子视

2019-07-19 15:47发布

我有一个应用程序UIScrollView添加为一个子视图UIView 。 我已经添加UITextFieldUITextview作为一个子视图UIScrollView 。我想取消键盘当我在滚动视图挖掘。 我怎样才能做到这一点?

Answer 1:

只需添加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];
}


Answer 2:

在iOS中7,你可以很容易地做到这一点。

scrollView.keyboardDismissMode = UIScrollViewKeyboardDismissModeInteractive;


Answer 3:

试试这个,

- (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];
}


Answer 4:

当我加入了手势的子类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


文章来源: dismissing the keyboard from a UITextField,UITextView as a subview of UIScrollView?