UITextField基本设置
实现其代理的方法
注:a、textField当前正在输入的文本框,text文本是当前输入的文本框的上一次输入结束时的文本
b、range 的location是textField的最后一个字符位置,既extField.text的(length),range 的length一直是0
c、string是当前输入的字符
NSString * toBeString = [textField.text stringByReplacingCharactersInRange:range withString:string];
在输入前的文本内容textField.text最后加上当前输入的字符string,得到当前文本框的内容
#pragma mark - textField delegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string;
{
NSString * toBeString = [textField.text stringByReplacingCharactersInRange:range withString:string]; //得到输入框的内容
NSLog(@"rang: from %ld to %ld ",range.location, range.length);
if (self.ipTextField == textField) //判断是否时我们想要限定的那个输入框
{
if ([toBeString length] > 15) { //如果输入框内容大于15则弹出警告
NSLog(@"ipTextField 超过最大数");
return NO;
}
}
if (self.roomNumTextField == textField) {
if ([toBeString length] == 4) {
self.ipTextField.text = [self buildIPStringWithString:toBeString];
}
if ([toBeString length] > 4) { //如果输入框内容大于3则弹出警告
NSLog(@"roomNumTextField 超过最大数");
return NO;
}
}
return YES;
}
附带检测字符串是否符合ip地址规范
//检查ip地址是否符合规范
- (BOOL)isIPAddressWithString:(NSString *)string{
if (string.length > 15) {
return false;
}
NSInteger from = 0; //记录截取的初始位置
NSInteger cutCount = 0; //记录截取次数
NSInteger length = string.length;
// NSInteger to = 0; //截取长度i-from+1
for (NSInteger i = 0; i < length; i++) {
unichar charactor = [string characterAtIndex:i];
//判断字符规范
if ( !((charactor>= 48 && charactor<=57) || charactor==46) ) {
return false;
}
//截取,判读是否在ip地址范围
if ((charactor==46) || (i==length-1)) {
NSInteger tempInt = [[string substringWithRange:NSMakeRange(from, (i-from+1))] integerValue];
//NSLog(@"%ld", tempInt);
if (!(tempInt >= 0 && tempInt <= 255)) {
return false;
}
from = i+1;
cutCount++;
}
}
//判断截取次数是否满足
if (cutCount != 4) {
return false;
}
//通过所有检测
return true;
}