美文网首页
iOS最完美的UITextField中输入金额,只能输入数字和小

iOS最完美的UITextField中输入金额,只能输入数字和小

作者: f79774d6d6bb | 来源:发表于2018-09-06 19:30 被阅读0次

@property(nonatomic,assign)BOOLisHaveDian;

@property(nonatomic,assign)BOOLisFirstZero;

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

if(textField ==self.amountTextField) {

if([textField.textrangeOfString:@"."].location==NSNotFound) {

_isHaveDian=NO;

}

if([textField.textrangeOfString:@"0"].location==NSNotFound) {

_isFirstZero=NO;

}

if([stringlength]>0)

{

unicharsingle=[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;

}

NSRangeran=[textField.textrangeOfString:@"."];

inttt=(int)(range.location-ran.location);

if(tt <=2){

returnYES;

}else{

returnNO;

}

}elseif(_isFirstZero&&!_isHaveDian){

//首位有0没.不能再输入0

returnNO;

}else{

returnYES;

}

}else{

if(_isHaveDian){

//存在小数点,保留两位小数

NSRangeran=[textField.textrangeOfString:@"."];

inttt= (int)(range.location-ran.location);

if(tt <=2){

returnYES;

}else{

returnNO;

}

}elseif(_isFirstZero&&!_isHaveDian){

//首位有0没点

returnNO;

}else{

returnYES;

}

}

}else{

//输入的数据格式不正确

returnNO;

}

}else{

returnYES;

}

}

returnYES;

}

相关文章

网友评论

      本文标题:iOS最完美的UITextField中输入金额,只能输入数字和小

      本文链接:https://www.haomeiwen.com/subject/vscfgftx.html