如何在iPhone上通过返回按钮点击隐藏UIViewController中的键盘

8

你好,我找到一些类似的问题,但是它们都涉及textView。我有一个ViewController,其中包含一个scrollView、6个文本框和一个textView。我想要一个函数,在点击“完成/返回”按钮时隐藏键盘。我已经实现了resignFirstResponder函数,可以在点击scrollView之外的区域时隐藏键盘,但这不完全符合我的要求,因为我也希望在点击按钮时隐藏它。

感谢任何帮助。

4个回答

15

创建一个符合UITextFieldDelegate协议的类,并将文本字段的代理设置为该类的实例。实现方法:

- (BOOL)textFieldShouldReturn:(UITextField *)textField

如下所示:

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

5

嗨,我发现对于文本字段,需要在viewdidload中添加以下行:

textFieldOne.returnKeyType = UIReturnKeyDone;
    textFieldCislo.delegate = self;
textFieldTwo.returnKeyType = UIReturnKeyDone;
    textFieldCislo.delegate = self;
...

并且这个实现方法如下:
-(BOOL)textFieldShouldReturn:(UITextField *)theTextField {

    if (theTextField == textFieldOne) {
        [textFieldOne resignFirstResponder];
    }
...
}

2
在底部添加 "return YES;" 以消除警告。还需在接口中添加 " <UITextFieldDelegate>" 以消除更多警告。 - Sunkas

3
您可以使用此方法,在视图中的任何位置点击即可隐藏键盘。
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}

2

经过一番寻找,我总结出了以下内容,而且它非常有效。

.h

//
//  ViewController.h
//  demoKeyboardScrolling
//
//  Created by Chris Cantley on 11/14/13.
//  Copyright (c) 2013 Chris Cantley. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController <UITextFieldDelegate>

// Connect your text field to this the below property.
@property (weak, nonatomic) IBOutlet UITextField *theTextField;

@end

.m

//
//  ViewController.m
//  demoKeyboardScrolling
//
//  Created by Chris Cantley on 11/14/13.
//  Copyright (c) 2013 Chris Cantley. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController



- (void)viewDidLoad
{
    [super viewDidLoad];
    // _theTextField is the name of the parameter designated in the .h file. 
    _theTextField.returnKeyType = UIReturnKeyDone;
    [_theTextField setDelegate:self];

}

// This part is more dynamic as it closes any text field when pressing return.  
// You might want to control every single text field separately but that isn't 
// what this code do.
-(void)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
}


@end

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接