一、设置输入内容的长度
1、监听方法
iOS UITextField限制字符长度
2、UITextField代理方法
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString: ALPHANUM ] invertedSet];
NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
if (textField == self.passWordField ) {
//这里的if时候为了获取删除操作,如果没有次if会造成当达到字数限制后删除键也不能使用的后果.
if (range.length == 1 && string.length == 0) {
return YES;
}
//so easy
else if (6<=self.passWordField.text.length && self.passWordField.text.length >=8 ) {
self.passWordField.text = [textField.text substringToIndex:8];
[textField resignFirstResponder];
return NO;
}
}else if ( textField == self.repwdField){
//这里的if时候为了获取删除操作,如果没有次if会造成当达到字数限制后删除键也不能使用的后果.
if (range.length == 1 && string.length == 0) {
return YES;
}
//so easy
else if ( 6<=self.repwdField.text.length && self.repwdField.text.length >=8) {
self.repwdField.text = [textField.text substringToIndex:8];
[textField resignFirstResponder];
return NO;
}
}
return [string isEqualToString:filtered];;
}
二、设置占位符文字字体大小、颜色、对齐方式
textField.placeholder = @"xxxx";
[textField setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"];
[textField setValue:[UIFont boldSystemFontOfSize:16] forKeyPath:@"_placeholderLabel.font"];
//------设置placeholder的大小后,如果不是系统默认大小,会出现垂直不居中的情况,解决如下
NSMutableParagraphStyle *style = [textField.defaultTextAttributes[NSParagraphStyleAttributeName] mutableCopy];
style.minimumLineHeight = textField.font.lineHeight - (textField.font.lineHeight - [UIFont systemFontOfSize:13.0f].lineHeight) / 2.0; //[UIFont systemFontOfSize:13.0f]是设置的placeholder的字体
textField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"请输入密码" attributes:@{NSParagraphStyleAttributeName : style}];
//------如果输入文字不居中,placeholder不居中,重写系统方法
-(CGRect)editingRectForBounds:(CGRect)bounds;
-(CGRect)placeholderRectForBounds:(CGRect)bounds;
//设置UITextField的textAlignment属性为NSTextAlignmentRight,placeholder文字也就靠右对齐了,输入光标也从右边开始
三、设置text文字字体大小、颜色
_nameTextField.textColor = [UIColor grayColor];
四、UITextField输入时候,默认文字偏移问题的解决办法
//不要设置清楚样式
//textField.clearButtonMode = UITextFieldViewModeWhileEditing;
textField.textAlignment =NSTextAlignmentRight;