ios 通过触摸 UITableView 的背景关闭键盘

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2321038/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 16:58:06  来源:igfitidea点击:

Dismiss keyboard by touching background of UITableView

iosuitableviewuikeyboard

提问by Hua-Ying

I have a UITableViewwith UITextFields as cells. I would like to dismiss the keyboard when the background of the UITableViewis touched. I'm trying to do this by creating a UIButtonthe size of the UITableViewand placing it behind the UITableView. The only problem is the UIButtonis catching all the touches even when the touch is on the UITableView. What am I doing wrong?

我有一个UITableViewUITextFieldS作为细胞。当UITableView触摸的背景时,我想关闭键盘。我试图通过创建UIButton的大小UITableView并将其放在UITableView. 唯一的问题是UIButton即使触摸在 UITableView 上,也会捕获所有触摸。我究竟做错了什么?

Thanks!

谢谢!

回答by mixja

This is easily done by creating a UITapGestureRecognizerobject (by default this will detect a "gesture" on a single tap so no further customization is required), specifying a target/action for when the gesture is fired, and then attaching the gesture recognizer object to your table view.

这很容易通过创建一个UITapGestureRecognizer对象(默认情况下,这将在单击时检测“手势”,因此不需要进一步定制),指定手势触发时的目标/动作,然后附加手势识别器对象来轻松完成到您的表视图。

E.g. Perhaps in your viewDidLoadmethod:

例如,也许在您的viewDidLoad方法中:

UITapGestureRecognizer *gestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyboard)];
[self.tableView addGestureRecognizer:gestureRecognizer];

And the hideKeyboardmethod might look like this:

hideKeyboard方法可能如下所示:

- (void) hideKeyboard {
    [textField1 resignFirstResponder];
    [textField2 resignFirstResponder];
    ...
    ...
}

Note that the gesture is not fired when touching inside a UITextFieldobject. It is fired though on the UITableViewbackground, footer view, header view and on UILabelsinside cells etc.

请注意,触摸UITextField对象内部时不会触发手势。它在UITableView背景、页脚视图、标题视图和UILabels内部单元格等上被触发。

回答by Azbuky

The UITapGestureRecognizer solution works with table cell selection if you set:

如果您设置,则 UITapGestureRecognizer 解决方案适用于表格单元格选择:

gestureRecognizer.cancelsTouchesInView = NO;

回答by Saad

Here is a best way to do this. Just do this

这是执行此操作的最佳方法。就这样做

[self.view endEditing:YES];

or

或者

[[self.tableView superView] endEditing:YES];

回答by Ben

You can also do it from Storyboard: enter image description here

您也可以从 Storyboard 执行此操作: 在此处输入图片说明

回答by Rajive Jain

As UITableViewis a subclass of UIScrollView, implementing one delegate method below provides an extremely easy, quick solution. No need to even involve resignFirstRespondersince view hierarchy introspects and finds the current responder and asks it to resign it's responder status.

作为UITableView的子类UIScrollView,在下面实现一个委托方法提供了一个非常简单、快速的解决方案。甚至不需要参与,resignFirstResponder因为视图层次结构会自省并找到当前的响应者并要求它放弃它的响应者状态。

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self.view endEditing:YES];
}

And remember to add UIScrollViewDelegateto header file.

并记得添加UIScrollViewDelegate到头文件中。

回答by bbeckford

Firstly, listen for scrollViewWillBeginDraggingin your UIViewControllerby adding the UIScrollViewDelegate:

首先,听scrollViewWillBeginDraggingUIViewController的加入UIScrollViewDelegate

In .h file:

在 .h 文件中:

@interface MyViewController : UIViewController <UIScrollViewDelegate> 

In .m file:

在 .m 文件中:

- (void)scrollViewWillBeginDragging:(UIScrollView *)activeScrollView {

    [self dismissKeyboard];

}

Then listen for other interactions:

然后监听其他交互:

- (void)setupKeyboardDismissTaps {

    UISwipeGestureRecognizer *swipeUpGestureRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(dismissKeyboard)];
    swipeUpGestureRecognizer.cancelsTouchesInView = NO;
    swipeUpGestureRecognizer.direction = UISwipeGestureRecognizerDirectionUp;
    [self.tableView addGestureRecognizer:swipeUpGestureRecognizer];

    UISwipeGestureRecognizer *swipeDownGestureRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(dismissKeyboard)];
    swipeDownGestureRecognizer.cancelsTouchesInView = NO;
    swipeDownGestureRecognizer.direction = UISwipeGestureRecognizerDirectionDown;
    [self.tableView addGestureRecognizer:swipeDownGestureRecognizer];

    UISwipeGestureRecognizer *swipeLeftGestureRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(dismissKeyboard)];
    swipeLeftGestureRecognizer.cancelsTouchesInView = NO;
    swipeLeftGestureRecognizer.direction = UISwipeGestureRecognizerDirectionLeft;
    [self.tableView addGestureRecognizer:swipeLeftGestureRecognizer];

    UISwipeGestureRecognizer *swipeRightGestureRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(dismissKeyboard)];
    swipeRightGestureRecognizer.cancelsTouchesInView = NO;
    swipeRightGestureRecognizer.direction = UISwipeGestureRecognizerDirectionRight;
    [self.tableView addGestureRecognizer:swipeRightGestureRecognizer];


    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissKeyboard)];
    tapGestureRecognizer.cancelsTouchesInView = NO;
    [self.tableView addGestureRecognizer:tapGestureRecognizer];

}

Then implement dismissKeyboard:

然后执行dismissKeyboard

- (void)dismissKeyboard {

    NSLog(@"dismissKeyboard");

    [yourTextFieldPointer resignFirstResponder];

}

And if, like me, you wanted to dismiss the keyboard for a UITextField inside a custom table cell:

如果像我一样,您想关闭自定义表格单元格内 UITextField 的键盘:

- (void)dismissKeyboard {

    NSLog(@"dismissKeyboard");

    CustomCellClass *customCell = [tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
    [customCell.textFieldInCell resignFirstResponder]; 

}

Hope that helps anyone searching!!

希望能帮到大家搜索!!

回答by Dom Bryan

tableView.keyboardDismissMode = .onDrag

回答by Biodave

Here's the swift version for your coding pleasure:

这是您编码乐趣的快速版本:

It adds a tap gesture recognizer then dismisses the keyboard. No outlet for the TextField is required!

它添加了一个点击手势识别器,然后关闭键盘。不需要 TextField 的出口!

override func viewDidLoad() {
    super.viewDidLoad()
    view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "handleTap:"))
}

func handleTap(sender: UITapGestureRecognizer) {
    if sender.state == .Ended {
        view.endEditing(true)
    }
    sender.cancelsTouchesInView = false
}

回答by Ivan Smetanin

There is Swift 3 version without blocking taps on cells.

有 Swift 3 版本,不会阻止点击单元格。

In viewDidLoad()method:

viewDidLoad()方法中:

let dismissKeyboardGesture = UITapGestureRecognizer(target: self, action: #selector(hideKeyboard))
dismissKeyboardGesture.cancelsTouchesInView = false
tableView.addGestureRecognizer(dismissKeyboardGesture)

And hideKeyboardlooks like this:

而且hideKeyboard是这样的:

func hideKeyboard() {
    view.endEditing(true)
}

回答by sha

I did it like this:

我是这样做的:

Create a method in your TableViewController to deactivate first responder (which would be your TextBox at that point)

在您的 TableViewController 中创建一个方法来停用第一响应者(此时将是您的 TextBox)

- (BOOL)findAndResignFirstResonder:(UIView *)stView {
    if (stView.isFirstResponder) {
        [stView resignFirstResponder];
        return YES;     
    }

    for (UIView *subView in stView.subviews) {
        if ([self findAndResignFirstResonder:subView]) {
            return YES;
        }
    }
    return NO;
}

In tableView:didSelectRowAtIndexPath:call the previous method:

tableView:didSelectRowAtIndexPath:调用之前的方法时:

- (void)tableView:(UITableView *)tableView
                             didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    ...
    [self findAndResignFirstResonder: self.view];
    ...
}