Hide keyboard by touching background of UITableView

早过忘川 提交于 2019-12-23 04:16:13

问题


I was searching some optimized method to hide keyboard on background tap when UITextFields are in a UITableViewCell. I have made some code Hope this would help you.


回答1:


Doing hittest doest seem to be the right way

You can implement the touch events on the View on which the tableView resides, like below.

Also assign the textField Object to a member variable in textFieldDidBeginEditing, so you will be able to resign the particular text field for which the keyborad is shown.

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [textFieldObject resignFirstResponder];
}



回答2:


I made a category of tableview for hiding the keyboard on background tap while tableview contains textfield.

My header file:

#import <UIKit/UIKit.h>
#import "Utility.h"

@interface UITableView (HitTest)

@end

My implementation file:

#import "UITableView+HitTest.h"

@implementation UITableView (HitTest)

UITableViewCell *activeCell;

-(UIView*) hitTest:(CGPoint)point withEvent:(UIEvent*)event
{
    NSInteger iterations = 0;
    // check to see if the hit is in this table view
    if ([self pointInside:point withEvent:event])
    {
        UITableViewCell* newCell = nil;

        // hit is in this table view, find out 
        // which cell it is in (if any)
        for (UITableViewCell* aCell in self.visibleCells)
        {
            iterations ++;
            if ([aCell pointInside:[self convertPoint:point toView:aCell] withEvent:event])
            {
                newCell = aCell;
                break;
            }
        }
        if (!newCell)
        { 
            for (UIView *view in activeCell.subviews)
            {
                iterations++;
                if ([view isFirstResponder])
                {
                    [view resignFirstResponder];
                    break;
                }
            }
        }
        else
        {
            activeCell = newCell;
        }
        NSLog(@"total Iterations:%d",iterations);
    }

    // return the super's hitTest result
    return [super hitTest:point withEvent:event];   
}    

@end

This is working fine for me.



来源:https://stackoverflow.com/questions/11260369/hide-keyboard-by-touching-background-of-uitableview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!