需要加入UITextFieldDelegate协议
- (void)viewDidLoad
{[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
UITextField *textTest = [[UITextField alloc] initWithFrame:CGRectMake(50, 50, 100, 30)];
textTest.text = @"myText";
textTest.delegate = self;//设置delegate为自己,不然按下Done键键盘消失不了
//设置框类型
[textTest setBorderStyle:UITextBorderStyleRoundedRect];
// textTest.borderStyle = UITextBorderStyleRoundedRect;
textTest.placeholder = @"输入"; //默认显示的内容
textTest.secureTextEntry = NO; //是否以密码形式显示
textTest.returnKeyType = UIReturnKeyDone; //设置键盘返回形式
textTest.clearButtonMode = UITextFieldViewModeWhileEditing; //输入内容后会显示个X
textTest.keyboardType = UIKeyboardTypeDefault; //键盘显示类型
textTest.autocorrectionType = UITextAutocorrectionTypeNo; //是否自动提醒功能
textTest.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter; //设置输入方式
textTest.autoresizingMask = UIViewAutoresizingFlexibleWidth; //自适应宽度
textTest.tag = 10;
[self.view addSubview:textTest];
}
//开始
-(void)textFieldDidBeginEditing:(UITextField *)textField
{
}
//结束
-(void)textFieldDidEndEditing:(UITextField *)textField{
}
//按Done键键盘消失
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
UITextField *text = (UITextField*)[self.view viewWithTag:10];
[text resignFirstResponder];
return YES;
}
//按非键盘位置的其它任意位置让键盘消失
//该方法需要先把XIB里的Objects下的UIView类名改为UIControl,然后右键点击Objects下的Control,把鼠标放开事件连线到File`s Owner
- (IBAction)backgroundTap:(id)sender {
UITextField *text = (UITextField*)[self.view viewWithTag:10];
[text resignFirstResponder];
}