Jak programowo wyłączyć klawiaturę iOS po naciśnięciu return

Stworzyłem UITextField programowo czyniąc UITextField właściwością viewcontrollera. Muszę odrzucić klawiaturę z powrotem i dotykiem na ekranie. Udało mi się uzyskać dotyk ekranu, aby odrzucić, ale naciśnięcie powrotu nie działa.

Widziałem, jak to zrobić za pomocą storyboardów i przydzielając i inicjując obiekt UITextField bezpośrednio bez tworzenia go jako właściwości. Możliwe do zrobienia?

.h

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController <UITextFieldDelegate>

@property (strong, atomic) UITextField *username;

@end

.m

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    // Do any additional setup after loading the view, typically from a nib.

    self.view.backgroundColor = [UIColor blueColor];
    self.username = [[UITextField alloc] initWithFrame:CGRectMake(100, 25, 80, 20)];
    self.username.placeholder = @"Enter your username";
    self.username.backgroundColor = [UIColor whiteColor];
    self.username.borderStyle = UITextBorderStyleRoundedRect;
    if (self.username.placeholder != nil) {
        self.username.clearsOnBeginEditing = NO;
    }
    _username.delegate = self; 

    [self.view addSubview:self.username];
    [_username resignFirstResponder];

}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    NSLog(@"touchesBegan:withEvent:");
    [self.view endEditing:YES];
    [super touchesBegan:touches withEvent:event];
}

@end
Author: Cœur, 2013-09-12

21 answers

Prosty sposób polega na podłączeniu delegata UITextField do self (self.mytestField.delegate = self) i odrzuceniu klawiatury w metodzie textFieldShouldReturn za pomocą [textField resignFirstResponder];

Innym sposobem odrzucenia klawiatury jest:

[self.view endEditing:YES];

Umieść [self.view endEditing:YES]; gdzie chcesz zamknąć klawiaturę (Zdarzenie przycisku, Zdarzenie dotykowe itp.).

 232
Author: Nitin Gohel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-01-14 05:25:04

Dodaj metodę delegata UITextField w następujący sposób:

@interface MyController : UIViewController <UITextFieldDelegate>

I ustaw swoje textField.delegate = self;, a następnie dodaj dwie metody delegowania UITextField

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{   
    return YES;
}

// It is important for you to hide the keyboard
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}
 28
Author: iPatel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-04-04 04:18:06

//ukryj klawiaturę dotykając tła w widoku

- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [[self view] endEditing:YES];
}
 23
Author: Vijay Dokrimare,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-08-05 08:04:05

Po prostu użyj tego w języku swift, aby odrzucić klawiaturę:

UIApplication.sharedApplication().sendAction("resignFirstResponder", to:nil, from:nil, forEvent:nil)

Swift 3

UIApplication.shared.sendAction(#selector(UIResponder.resign‌​FirstResponder), to: nil, from: nil, for: nil)
 18
Author: Chathuranga Silva,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-07-03 10:38:47

Spróbuj zorientować się, czym jest osoba udzielająca pierwszej pomocy w hierarchii widoku systemu iOS. Gdy pole tekstowe staje się aktywne (lub pierwszy responder) po dotknięciu wewnątrz niego (lub podaniu go messasge becomeFirstResponder programowo), wyświetla klawiaturę. Aby więc usunąć pole tekstowe z bycia pierwszym odpowiedzialnym, należy przekazać do niego wiadomość resignFirstResponder.

[textField resignFirstResponder];

I aby ukryć klawiaturę na przycisku powrotu, należy zaimplementować jej metodę delegate textFieldShouldReturn: i przekazać wiadomość resignFirstResponder.

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}
 6
Author: Zen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-09-12 04:45:50

W aplikacji Delegat możesz napisać

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.window endEditing:YES];
}

Użyj tego sposobu, nie możesz pisać za dużo kodu.

 6
Author: DKong,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-06-04 10:09:32

Oto, czego używam w moim kodzie. To działa jak urok!

W yourviewcontroller.h add:

@property (nonatomic) UITapGestureRecognizer *tapRecognizer;

Teraz w .plik m, dodaj to do funkcji ViewDidLoad:

- (void)viewDidLoad {
    [super viewDidLoad];

    //Keyboard stuff
    tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap:)];
    tapRecognizer.cancelsTouchesInView = NO;
    [self.view addGestureRecognizer:tapRecognizer];
}

Dodaj również tę funkcję w .plik m:

- (void)handleSingleTap:(UITapGestureRecognizer *) sender
{
    [self.view endEditing:YES];
}
 6
Author: Takide,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-07-21 05:41:38

SWIFT 4:

self.view.endEditing(true)

Lub

Ustaw delegata pola tekstowego do bieżącego kontrolera viewcontrollera, a następnie:

func textFieldShouldReturn(_ textField: UITextField) -> Bool {

    textField.resignFirstResponder()

    return true

}

Objective-C:

[self.view endEditing:YES];

Lub

Ustaw delegata pola tekstowego do bieżącego kontrolera viewcontrollera, a następnie:

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];

    return YES;
}
 5
Author: Sam,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-01-16 05:15:00

Aby wyłączyć klawiaturę po pojawieniu się klawiatury, są 2 przypadki ,

  1. Gdy pole UITextField jest wewnątrz UIScrollView

  2. Gdy pole UITextField znajduje się Poza UIScrollView

2.gdy pole UITextField znajduje się poza UIScrollView nadpisanie metody w podklasie UIViewController

Musisz również Dodać delegata dla wszystkich UITextView

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}
  1. W widoku przewijania, stukanie Na Zewnątrz nie uruchomi się żadne zdarzenie, więc w takim przypadku Użyj rozpoznawania gestów stukania , Przeciągnij i upuść UITapGesture dla widoku przewijania i Utwórz dla niego IBAction .

Aby utworzyć IBAction, naciśnij ctrl+ kliknij UITapGesture i przeciągnij go do .h plik viewcontroller.

Tutaj nazwałem tappedEvent jako nazwę mojej akcji

- (IBAction)tappedEvent:(id)sender {
      [self.view endEditing:YES];  }

Podane informacje pochodzą z poniższego linku, proszę zapoznać się z Więcej informacji lub skontaktuj się ze mną, jeśli nie rozumiesz o danych.

Http://samwize.com/2014/03/27/dismiss-keyboard-when-tap-outside-a-uitextfield-slash-uitextview/

 3
Author: ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-12-02 05:31:37

Dla grupy UITextViewS wewnątrz ViewController:

Swift 3.0

for view in view.subviews {
    if view is UITextField {
        view.resignFirstResponder()
    }
}

Objective-C

// hide keyboard before dismiss
for (UIView *view in [self.view subviews]) {
    if ([view isKindOfClass:[UITextField class]]) {
        // no need to cast
        [view resignFirstResponder];
    }
}
 3
Author: Matias Elorriaga,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-01-04 22:05:38

Wiem, że na to odpowiedzieli inni, ale znalazłem inny artykuł, który obejmował również brak zdarzenia w tle-tableview lub scrollview.

Http://samwize.com/2014/03/27/dismiss-keyboard-when-tap-outside-a-uitextfield-slash-uitextview/

 2
Author: zainoz.zaini,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-11-20 23:06:06

Ponieważ znaczniki mówią tylko iOS, zamieszczę odpowiedź dla Swift 1.2 i iOS 8.4, dodaj je w swojej klasie swift kontrolera widoku:

// MARK: - Close keyboard when touching somewhere else
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {

    self.view.endEditing(true)

}

// MARK: - Close keyboard when return pressed
func textFieldShouldReturn(textField: UITextField!) -> Bool {

    textField.resignFirstResponder()

    return true
}
// MARK: -

Nie zapomnij również dodać UITextFieldDelegate w deklaracji klasy i ustawić swoje pola tekstowe delegować na self (widok).

 2
Author: Juan Boero,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-08-06 16:18:05

W Swift 3

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.view.endEditing(true)
    }

Lub

func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        if textField == yourtextfieldName
        {
            self.resignFirstResponder()
            self.view.endEditing(true)
        }
    }
 2
Author: Rob-4608,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-12-13 16:49:45

Najpierw musisz dodać textfield delegete in .plik H. if not declare (BOOL)textFieldShouldReturn:(UITextField *)textField ta metoda nie called.so najpierw dodaj delegata i napisz kod ukrywania klawiatury do tej metody.

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}
Spróbuj tego..
 1
Author: Jitendra,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-09-12 04:50:50

Więc oto, co zrobiłem, aby go odrzucić po dotknięciu tła lub powrotu. Musiałem dodać delegate = self w viewDidLoad, a następnie również metody delegate później w .pliki M.

.h
#import <UIKit/UIKit.h>

@interface ViewController : UIViewController <UITextFieldDelegate>


@property (strong, atomic) UITextField *username;

@end

.m
- (void)viewDidLoad
{
    [super viewDidLoad];

    // Do any additional setup after loading the view, typically from a nib.

    self.view.backgroundColor = [UIColor blueColor];
    self.username = [[UITextField alloc] initWithFrame:CGRectMake(100, 25, 80, 20)];
    self.username.placeholder = @"Enter your username";
    self.username.backgroundColor = [UIColor whiteColor];
    self.username.borderStyle = UITextBorderStyleRoundedRect;
    if (self.username.placeholder != nil) {
        self.username.clearsOnBeginEditing = NO;
    }
    self.username.delegate = self;
    [self.username resignFirstResponder];
    [self.view addSubview:self.username];


}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    return YES;
}



- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

@end
 1
Author: noobsmcgoobs,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-09-13 16:46:38

Dodaj Delegata : UITextFieldDelegate

@interface ViewController : UIViewController <UITextFieldDelegate>

A następnie dodaj tę metodę delegata

// to powinno działać idealnie

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}
 0
Author: Ravi_Parmar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-09-12 04:53:50
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[self.view.subviews enumerateObjectsUsingBlock:^(UIView* obj, NSUInteger idx, BOOL *stop) {
    if ([obj isKindOfClass:[UITextField class]]) {
        [obj resignFirstResponder];
    }
}];
}

Gdy używasz więcej niż jednego pola tekstowego na ekranie Dzięki tej metodzie nie musisz wspominać textfield za każdym razem jak

[textField1 resignFirstResponder];
[textField2 resignFirstResponder];
 0
Author: Harshad,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-07-21 07:55:53

Swift 2 :

Tak się robi wszystko !

Zamknij klawiaturę przyciskiem Done lub Touch outSide ,Next aby przejść do następnego wejścia.

Najpierw zmień tekst Return Key na Next w Storyboardzie.

override func viewDidLoad() {
  txtBillIdentifier.delegate = self
  txtBillIdentifier.tag = 1
  txtPayIdentifier.delegate  = self
  txtPayIdentifier.tag  = 2

  let tap = UITapGestureRecognizer(target: self, action: "onTouchGesture")
  self.view.addGestureRecognizer(tap)

}

func textFieldShouldReturn(textField: UITextField) -> Bool {
   if(textField.returnKeyType == UIReturnKeyType.Default) {
       if let next = textField.superview?.viewWithTag(textField.tag+1) as? UITextField {
           next.becomeFirstResponder()
           return false
       }
   }
   textField.resignFirstResponder()
   return false
}

func onTouchGesture(){
    self.view.endEditing(true)
}
 0
Author: Mojtabye,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-09-14 07:35:19

Jeśli nie znasz bieżącego kontrolera widoku lub textview, możesz użyć łańcucha odpowiedzi:

UIApplication.shared.sendAction(#selector(UIView.endEditing(_:)), to:nil, from:nil, for:nil)
 0
Author: coldfire,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-06-19 10:22:11

Dla swift 3-4 naprawiłem jak

func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
    return false
}

Po prostu skopiuj wklej w dowolnym miejscu na klasie. To rozwiązanie po prostu działa, jeśli chcesz, aby wszystkie UItextfield działały tak samo, lub jeśli masz tylko jeden!

 0
Author: hall.keskin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-12-13 11:18:41

Po prostu użyj tego w Objective-C, aby odrzucić klawiaturę:

[[UIApplication sharedApplication].keyWindow endEditing:YES];
 0
Author: Linc,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-09-28 02:25:21