// 1.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;
//return键变成什么键
textField.returnKeyType = UIReturnKeyDone;
//输入框中是否有个叉号,在什么时候显示,用于一次性删除输入框中的内容
textField.clearButtonMode = UITextFieldViewModeWhileEditing;
//再次编辑就清空
textField.clearsOnBeginEditing = YES;
//设置为YES时文本会自动缩小以适应文本窗口大小.默认是保持原来大小,而让长文本滚动
textField.adjustsFontSizeToFitWidth = YES;
//设置自动缩小显示的最小字体大小
textField.minimumFontSize = 20;
//设置键盘的样式
textField.keyboardType = UIKeyboardTypeNumberPad;
textField.delegate = self;
UIImageView *imgv=[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"right.png"]];
textField.rightView=imgv;//右侧图片
textField.rightViewMode = UITextFieldViewModeAlways;
textField.leftView=imgv;//左侧图片
textField.leftViewMode = UITextFieldViewModeAlways;
textField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;//垂直居中
//2.要实现的UITextFieldDelegate方法,回收键盘
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
return YES;
}
//开始编辑时触发,文本字段将成为first responder
- (void)textFieldDidBeginEditing:(UITextField *)textField{
}
//限制长度。字符
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
NSCharacterSet *cs;
NSString *str = @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
// 限制输入英文和数字
cs = [[NSCharacterSet characterSetWithCharactersInString: @"0123456789\n"]invertedSet];//输入数字和换行(注意这个\n,如果不写这个,Done按键将不会触发,如果用在SearchBar中,将会不触发Search事件,因为你自己限制不让输入\n)
NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs]componentsJoinedByString:@""];
BOOL canChange = [string isEqualToString:filtered];
return canChange;
}