.h文件
#import
#import"AppEnum.h"
@interfaceCommonTextField :UITextField
- (instancetype)initWithFrame:(CGRect)frame font:(UIFont*)font keyboardType:(UIKeyboardType)keyboardType placeholder:(NSString*)placeholder CommonTextFieldType:(eCommonTextFieldType)type;
@property(nonatomic,assign)NSIntegeriMaxLength;// 最大允许输入内容长度,不设置默认为50;
/* 是否支付相关需求
* 1.小数点后保存2位(可配置)
* 2.小数点不能作为第一位字符
* 3.第一位是0则第二位必然是小数点
* 4.只能包含一个小数点
*/
@property(nonatomic,assign)BOOLisPay;
@property(nonatomic,assign)NSIntegeriPointCount;// 保留小数点的位数
@end
.m文件
#import"CommonTextField.h"
#import"Tools.h"
@interfaceCommonTextField()
@property(nonatomic,assign)eCommonTextFieldTypeeCTextFieldType;
@end
@implementationCommonTextField
- (instancetype)initWithFrame:(CGRect)frame font:(UIFont*)font keyboardType:(UIKeyboardType)keyboardType placeholder:(NSString*)placeholder CommonTextFieldType:(eCommonTextFieldType)type
{
if(self= [superinitWithFrame:frame])
{
_iMaxLength=50;
_iPointCount=2;// 默认保存2位小数点
self.frame= frame;
self.font= font;
self.keyboardType= keyboardType;
self.placeholder= placeholder;
self.eCTextFieldType= type;
self.delegate=self;
}
returnself;
}
- (BOOL)textField:(UITextField*)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString*)string
{
if(range.length==1&& string.length==0)// 防止内容达到限制后无法删除的问题
{
returnYES;
}
if(range.location>_iMaxLength-1)// 输入时的内容限制
{
returnNO;
}
switch(self.eCTextFieldType)
{
caseeTextFieldOnlyNumber:
if(![ToolsisNumber:stringisContainPoint:NO])
{
returnNO;
}
break;
caseeTextFieldNumberAndPoint:
if(![ToolsisNumber:stringisContainPoint:YES])
{
returnNO;
}
if(_isPay)
{
if(![ToolsisPointAbout:textField.textiPointCount:_iPointCountinRange:rangereplacementString:string])
{
returnNO;
}
}
break;
default:
break;
}
returnYES;
}
// 此代理防止中文键盘联想词输入超过限制,以及粘贴进来的字符
- (void)textFieldDidChange:(UITextField*)textField
{
if(textField.text.length>_iMaxLength)
{
textField.text= [textField.textsubstringToIndex:_iMaxLength];
}
if(_eCTextFieldType==eTextFieldNumberAndPoint&&_isPay)
{
if([textField.textcontainsString:@"."])
{
NSArray*arrayTRF = [textField.textcomponentsSeparatedByString:@"."];
if(arrayTRF.count!=2)
{
return;
}
NSString*strR = arrayTRF[1];
if(strR.length==_iPointCount)
{
textField.text= [textField.textsubstringToIndex:textField.text.length];
}
}
}
}
- (void)textFieldDidEndEditing:(UITextField*)textField
{
if([textField.texthasSuffix:@"."] &&_isPay)
{
textField.text= [NSStringstringWithFormat:@"%@00", textField.text];
}
}
- (BOOL)textFieldShouldReturn:(UITextField*)textField
{
[textFieldresignFirstResponder];
returnYES;
}