_textField=[[UITextFieldalloc]initWithFrame:CGRectMake(10,100, 300, 40)];
_textField.placeholder=@"请输入手机号码";
_textField.delegate=self;
[_textFieldaddTarget:selfaction:@selector(textFieldChange:)forControlEvents:UIControlEventEditingChanged];
_textField.leftViewMode=UITextFieldViewModeAlways;
_textField.rightViewMode=UITextFieldViewModeAlways;
_textField.keyboardType=UIKeyboardTypeDecimalPad;
[self.viewaddSubview:_textField];
//只显示小数点后两位,以及不能出现两个小数点
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if (textField ==self.textField) {
if ([textField.textrangeOfString:@"."].location==NSNotFound) {
_isHaveDian =NO;
}
if ([textField.textrangeOfString:@"0"].location==NSNotFound) {
_isFirstZero =NO;
}
if ([stringlength]>0)
{
unichar single=[stringcharacterAtIndex:0];//当前输入的字符
if ((single >='0' && single<='9') || single=='.')//数据格式正确
{
if([textField.textlength]==0){
if(single =='.'){
//首字母不能为小数点
returnNO;
}
if (single =='0') {
_isFirstZero =YES;
returnYES;
}
}
if (single=='.'){
if(!_isHaveDian)//text中还没有小数点
{
_isHaveDian=YES;
returnYES;
}else{
returnNO;
}
}elseif(single=='0'){
if ((_isFirstZero&&_isHaveDian)||(!_isFirstZero&&_isHaveDian)) {
//首位有0有.(0.01)或首位没0有.(10200.00)可输入两位数的0
if([textField.textisEqualToString:@"0.0"]){
returnNO;
}
NSRange ran=[textField.textrangeOfString:@"."];
int tt=(int)(range.location-ran.location);
if (tt <=2){
returnYES;
}else{
returnNO;
}
}elseif (_isFirstZero&&!_isHaveDian){
//首位有0没.不能再输入0
returnNO;
}else{
returnYES;
}
}else{
if (_isHaveDian){
//存在小数点,保留两位小数
NSRange ran=[textField.textrangeOfString:@"."];
int tt= (int)(range.location-ran.location);
if (tt <=2){
returnYES;
}else{
returnNO;
}
}elseif(_isFirstZero&&!_isHaveDian){
//首位有0没点
returnNO;
}else{
returnYES;
}
}
}else{
//输入的数据格式不正确
returnNO;
}
}else{
returnYES;
}
}
returnYES;
}