.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;// 最大允許輸入內(nèi)容長(zhǎng)度,不設(shè)置默認(rèn)為50;
/* 是否支付相關(guān)需求
* 1.小數(shù)點(diǎn)后保存2位(可配置)
* 2.小數(shù)點(diǎn)不能作為第一位字符
* 3.第一位是0則第二位必然是小數(shù)點(diǎn)
* 4.只能包含一個(gè)小數(shù)點(diǎn)
*/
@property(nonatomic,assign)BOOLisPay;
@property(nonatomic,assign)NSIntegeriPointCount;// 保留小數(shù)點(diǎn)的位數(shù)
@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;// 默認(rèn)保存2位小數(shù)點(diǎn)
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)// 防止內(nèi)容達(dá)到限制后無(wú)法刪除的問(wèn)題
{
returnYES;
}
if(range.location>_iMaxLength-1)// 輸入時(shí)的內(nèi)容限制
{
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;
}
// 此代理防止中文鍵盤(pán)聯(lián)想詞輸入超過(guò)限制,以及粘貼進(jìn)來(lái)的字符
- (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;
}