UITextField编辑后关闭虚拟键盘方法笔记

UITextField编辑框经常会遇到关闭虚拟键盘的情况。总结一下,一下的方法。
  • 方法一:通过触摸背景关闭虚拟键盘
在RootViewController.h中,如下:
@interface RootViewController : UIViewController<UITextFieldDelegate> {

UITextField *nameTextField;
UITextField *numberTextField;
}

@property (nonatomic ,retain) UITextField *nameTextField;
@property (nonatomic,retain) UITextField *numberTextField;

-(IBAction)backgroundTap:(id)sender;


@end
在RootViewController.m中,如下:
#import "RootViewController.h"

@implementation RootViewController

@synthesize nameTextField;
@synthesize numberTextField;

- (void)viewDidLoad {
[super viewDidLoad];

//---set two textField
nameTextField = [[UITextField alloc] initWithFrame:CGRectMake(100, 120, 200, 30)];
numberTextField = [[UITextField alloc] initWithFrame:CGRectMake(100, 160, 200, 30)];
nameTextField.backgroundColor = [UIColor clearColor];
numberTextField.backgroundColor = [UIColor clearColor];
nameTextField.borderStyle = UITextBorderStyleRoundedRect;
numberTextField.borderStyle = UITextBorderStyleRoundedRect;
nameTextField.delegate = self;
numberTextField.delegate = self;
[self.view addSubview:nameTextField];
[self.view addSubview:numberTextField];

}
-(IBAction)backgroundTap:(id)sender

{

	[nameTextField resignFirstResponder];

	[numberTextField resignFirstResponder];

}

RootViewController本身带着一个view,通过IB,把view的底层类有UIView更改为UIControl。因为UIControl是UIView的一个子类,所以非常适合用于将view属性连接到UIControl实例。然后将view的触发的事件Touch Down连接到File's owner图标,然后选择backgroundTap:操作。完成链接。
  • 方法二:通过UITextFieldDelegate方法。
#pragma mark -
#pragma mark UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
//[nameTextField resignFirstResponder];
// [numberTextField resignFirstResponder];
[textField resignFirstResponder];//等于上面两行的代码

NSLog(@"textFieldShouldReturn");//测试用
return YES;
}
在手动编辑UITextField时,别忘了把代理方法写上。如上为: nameTextField.delegate = self; numberTextField = self;
  • 方法三

你可能感兴趣的:(UITextField)