//左视图,右视图
UIView* leftView = [[UIViewalloc]initWithFrame:CGRectMake(0,0,10,44)];
self.costomTextField.leftView= leftView;
self.costomTextField.leftViewMode = UITextFieldViewModeAlways;
UIView* rightView = [[UIViewalloc]initWithFrame:CGRectMake(86,0,10,44)];
self.costomTextField.rightView= rightView;
self.costomTextField.rightViewMode = UITextFieldViewModeAlways;
iOS 监听textfield的输入
[textField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
-(void)textFieldDidChange :(UITextField*)theTextField{
NSLog(@"text changed: %@", theTextField.text);
}
iOS 限制TextField输入长度
- (BOOL)textField:(UITextField*)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString*)string
{
if(range.length==1&& string.length==0) {
returnYES;
}
else if (self.typeMoneyTextField.text.length >= 9) {
self.typeMoneyTextField.text= [textField.textsubstringToIndex:9];
BGAVShow(@"超出数值范围");
returnNO;
}
else{
//没有小数点
if([textField.textrangeOfString:@"."].location==NSNotFound)
{
self.isHaveDecimal=NO;
}
//如果输入的字数大于1
if([stringlength] >0)
{
unicharsingle = [stringcharacterAtIndex:0];//当前输入的字符
//数据格式正确
if((single >='0'&& single <='9') || single =='.')
{
//首字母不能为0和小数点
if([textField.textlength] ==0)
{
if(single =='.')
{
BGAVShow(@"第一个数字不能为小数点");
[textField.textstringByReplacingCharactersInRange:rangewithString:@""];
returnNO;
}
if(single =='0')
{
BGAVShow(@"第一个数字不能为0");
[textField.textstringByReplacingCharactersInRange:rangewithString:@""];
returnNO;
}
}
//输入的字符是否是小数点
if(single =='.')
{
if(!self.isHaveDecimal)//text中还没有小数点
{
self.isHaveDecimal=YES;
returnYES;
}else{
BGAVShow(@"已经输入过小数点了");
[textField.textstringByReplacingCharactersInRange:rangewithString:@""];
returnNO;
}
}
else{
if(self.isHaveDecimal) {//存在小数点
//判断小数点的位数
NSRangeran = [textField.textrangeOfString:@"."];
if(range.location- ran.location<=3) {
returnYES;
}else{
BGAVShow(@"最多输入三位小数");
returnNO;
}
}else{//不存在小数点
returnYES;
}
}
}else{//输入的数据格式不正确
BGAVShow(@"输入的格式不正确");
[textField.text stringByReplacingCharactersInRange:range withString:@""];
returnNO;
}
}
else
{
returnYES;
}
}
}