UITextfield限制

2016-08-17  本文已影响22人  然亦伞

输入键盘设置

placeHolderTF.keyboardType = UIKeyboardTypeASCIICapable;//设置键盘类型,不能输入中文

placeHolderTF.secureTextEntry = YES;//加密显示

placeHolderTF.returnKeyType = UIReturnKeyDone;//键盘return按钮设置

监听输入框编辑变化

[self.withdrawCashNumberTextFieild addTarget:self action:@selector(withdrawCashNumberTextFieildValueChanged:) forControlEvents:UIControlEventEditingChanged];

- (void)withdrawCashNumberTextFieildValueChanged:(UITextField *)textField{

//只能输入两位小数

NSString *text = textField.text;

NSRange pointRange = [text rangeOfString:@"."];

if (pointRange.location != NSNotFound) {

NSString *subtext = [text substringFromIndex:pointRange.location + pointRange.length - 1];

if (subtext.length > 2) {

textField.text = [text substringToIndex:pointRange.location + 3];

}

}

}

//限制小数输入

#pragma mark - UITextField处理

- (BOOL)textField:(UITextField*)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString*)string

{

if(textField ==self.withdrawCashNumberTextFieild) {

//判断是否为删除字符,如果为删除则让执行

if(string.length==0) {

returnYES;

}

//获取输入框内字符串

NSString*text = textField.text;

//首位不能输.和0

if(text.length==0&& ([stringisEqualToString:@"."] || [stringisEqualToString:@"0"])) {

returnNO;

}

//判断是否有小数点

if([textrangeOfString:@"."].length) {

//不允许输双..

if([stringisEqualToString:@"."]){

returnNO;

}

//获取小数点后面字符串长度

if([textsubstringFromIndex:[textrangeOfString:@"."].location].length>2) {

returnNO;

}else{

returnYES;

}

}else{

returnYES;

}

}

returnYES;

}

限制文本长度

#pragma mark - UITextFieldDelegate

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{

//用户名25字内

if (textField == self.userNameTF) {

NSInteger strLength = textField.text.length - range.length + string.length;

if (strLength < kNameLengthLimit+1) {

return YES;

}else{

textField.text = [textField.text substringToIndex:kNameLengthLimit];

return NO;

}

}else if (textField == self.telNumberTF) {

//手机号码文本框限制只能输入11个数字

NSInteger strLength = textField.text.length - range.length + string.length;

return (strLength <= 11);

}

键盘return按钮点击响应textField代理事件

-(BOOL)textFieldShouldReturn:(UITextField *)textField

{

//此判断是为围堵姓名/邀请码等有中文的输入字数超限

if (textField.keyboardType == UIKeyboardTypeDefault) {

if (textField == self.userNameTF && textField.text.length > kNameLengthLimit) {

textField.text = [textField.text substringToIndex:kNameLengthLimit];

}

}

[textField resignFirstResponder];

return  YES;

}

上一篇下一篇

猜你喜欢

热点阅读