Umair
Umair

Reputation: 65

Hide keyboard by touching background of UITableView

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.

Upvotes: 1

Views: 1917

Answers (2)

Umair
Umair

Reputation: 65

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.

Upvotes: 1

Sj.
Sj.

Reputation: 1724

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

Upvotes: 1

Related Questions