看了刘伟老师的博客http://blog.csdn.net/iukey/,学到了很多。
UITextField同样继承自UIControl类所以基本的属性和方法通用,最好还是先了解UIControl类
UITextField的实现基本步骤
初始化和设置
设置委托
委托方法的实现
初始化和设置
textField = [[UITextField alloc] initWithFrame:CGRectMake(120.0f, 80.0f, 150.0f, 30.0f)];
[textField setBorderStyle:UITextBorderStyleRoundedRect]; //外框类型
textField.placeholder = @"password"; //默认显示的字
textField.secureTextEntry = YES; //密码
textField.autocorrectionType = UITextAutocorrectionTypeNo;
textField.autocapitalizationType = UITextAutocapitalizationTypeNone;
textField.returnKeyType = UIReturnKeyDone;
textField.clearButtonMode = UITextFieldViewModeWhileEditing; //编辑时会出现个修改X
textField.delegate = self;
设置委托
如果键盘挡住了文本框,画面自动上移
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
CGRect frame = self.view.frame;
// 键盘遮住了文本字段,视图整体上移
frame.origin.y -= 120;
frame.size.height += 120;
self.view.frame = frame;
}
之前的上移还要移回来
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
CGRect frame = self.view.frame;
frame.origin.y +=120;
frame.size.height -= 120;
self.view.frame = frame;
NSLog(@"textField:%@",textField);
//返回一个BOOL值,指名是否允许在按下回车键时结束编辑
//如果允许药调用resignFirstResponder方法,这会导致结束编辑,键盘会被收起
[textField resignFirstResponder];
return YES;
}
限制输入文本的长度
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if ([textField.text length] > MAXLENGTH)
{
textField.text = [textField.text substringToIndex:MAXLENGTH-1];
return NO;
}
return YES;
}