How to make the keyboard disappear?

I have a text box that displays in a UITableViewCell, and I want to be able to hide the keyboard when the user touches anywhere else on the screen, except for the text box. I know about [field resignFirstResponder];, but I don't know how to intercept strokes in the background of a UITableView to call "resignFirstResponder".

Any help would be greatly appreciated.

+3
source share
5 answers

The only way to do this is to subclass the UITableView, implement the touchhesBegan method in your UITableView subclass, and send the UITextField objects to the UITableView. Here's how it should look -

//  GRTableView.h
//  StackOverflow Example
//
//  Created by Raphael Caixeta on 8/13/10.
//  Copyright 2010 Raphael Caixeta. All rights reserved.
//

#import <UIKit/UIKit.h>


@interface GRTableView : UITableView <UITableViewDelegate> {

    UITextField *textField;

}

@property(nonatomic, retain) UITextField *textField;

@end

//
//  GRTableView.m
//  StackOverflow Example
//
//  Created by Raphael Caixeta on 8/13/10.
//  Copyright 2010 Raphael Caixeta. All rights reserved.
//

#import "GRTableView.h"

@implementation GRTableView
@synthesize textField;

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

- (void)dealloc {
    [super dealloc];
}


@end

, UITableView, . , .

+3

- (void)textFieldDidEndEditing:(UITextField *)textField UITextFieldDelegate.

0

: UIView, , , resignFirstResponder.

// somewhere in a view controller
UIView *backgroundView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
[self.view addSubview:backgroundView];

// in the touchesBegan:withEvent: method, for example
UITouch *touch = [[event allTouches] anyObject];

if ([field isFirstResponder] && [touch view] == backgroundView) {
    [field resignFirstResponder];
}

backgroundView touch , : withEvent: method:

UITouch *touch = [[event allTouches] anyObject];

if ([field isFirstResponder] && [touch view] != field) {
    [field resignFirstResponder];
}

! () field, .

0

:

    • (void) tableView: (UITableView *) tableView didSelectRowAtIndexPath: (NSIndexPath *) indexPath {}
    • (void) TextField: (UITextField *) TxtFld textDidChange: (NSString *) searchText {}

[TxtFld resignFirstResponder]; , , , [TxtFld resignFirstResponder]; TxtFld - UIText.

, . , , UITableviewCell. .

, , .

0

, " UITableView" " UIView ". UIButton , . , YES.

, NO.

UITouchUpInside , [textField resignFirstResponder] button.hidden = YES.

0

Source: https://habr.com/ru/post/1758756/


All Articles