#import"ViewController.h"
staticNSIntegerCharacterCount =8;
@interfaceViewController()
@property(weak,nonatomic)IBOutletUILabel *totalCharacterLabel;
@property(weak,nonatomic)IBOutletUITextField *nameField;
@end
@implementationViewController
- (void)viewDidLoad{
[superviewDidLoad];
[self.nameFieldaddTarget:selfaction:@selector(textFieldChanged:)forControlEvents:UIControlEventEditingChanged];
self.nameField.delegate= self;
//Do any additional setup after loading the view, typically from a nib.
}
#pragma mark- Method
- (void)textFieldChanged:(UITextField *)textField{
NSString*toBeString = textField.text;
if(![selfisInputRuleAndBlank:toBeString]) {
textField.text= [selfdisable_emoji:toBeString];
return;
}
NSString*lang = [[textFieldtextInputMode]primaryLanguage];//获取当前键盘输入模式
//简体中文输入,第三方输入法(搜狗)所有模式下都会显示“zh-Hans”
if([langisEqualToString:@"zh-Hans"]) {
UITextRange *selectedRange = [textFieldmarkedTextRange];
//获取高亮部分
UITextPosition *position = [textFieldpositionFromPosition:selectedRange.startoffset:0];
//没有高亮选择的字,则对已输入的文字进行字数统计和限制
if(!position) {
NSString*getStr = [selfgetSubString:toBeString];
if(getStr && getStr.length>0) {
textField.text= getStr;
}
}
}else{
NSString*getStr = [selfgetSubString:toBeString];
if(getStr && getStr.length>0) {
textField.text= getStr;
}
}
}
/**
* 字母、数字、中文正则判断(不包括空格)
*/
- (BOOL)isInputRuleNotBlank:(NSString*)str{
NSString*pattern =@"^[a-zA-Z\u4E00-\u9FA5\\d]*$";
NSPredicate*pred = [NSPredicatepredicateWithFormat:@"SELFMATCHES%@", pattern];
BOOLisMatch = [predevaluateWithObject:str];
if(!isMatch) {
NSString*other =@"➋➌➍➎➏➐➑➒";
unsignedlonglen=str.length;
for(inti=0;i
{
unichara=[strcharacterAtIndex:i];
if(!((isalpha(a))
||(isalnum(a))
||((a=='_') || (a =='-'))
||((a >= 0x4e00 && a <= 0x9fa6))
||([otherrangeOfString:str].location!=NSNotFound)
))
returnNO;
}
returnYES;
}
returnisMatch;
}
/**
* 字母、数字、中文正则判断(包括空格)(在系统输入法中文输入时会出现拼音之间有空格,需要忽略,当按return键时会自动用字母替换,按空格输入响应汉字)
*/
- (BOOL)isInputRuleAndBlank:(NSString*)str{
NSString*pattern =@"^[a-zA-Z\u4E00-\u9FA5\\d\\s]*$";
NSPredicate*pred = [NSPredicatepredicateWithFormat:@"SELFMATCHES%@", pattern];
BOOLisMatch = [predevaluateWithObject:str];
returnisMatch;
}
/**
* 过滤字符串中的emoji
*/
- (NSString*)disable_emoji:(NSString*)text{
NSRegularExpression*regex = [NSRegularExpressionregularExpressionWithPattern:@"[^\\u0020-\\u007E\\u00A0-\\u00BE\\u2E80-\\uA4CF\\uF900-\\uFAFF\\uFE30-\\uFE4F\\uFF00-\\uFFEF\\u0080-\\u009F\\u2000-\\u201f\r\n]"options:NSRegularExpressionCaseInsensitiveerror:nil];
NSString*modifiedString = [regexstringByReplacingMatchesInString:text
options:0
range:NSMakeRange(0, [textlength])
withTemplate:@""];
returnmodifiedString;
}
/**
* 获得 CharacterCount长度的字符
*/
-(NSString*)getSubString:(NSString*)string
{
//NSStringEncoding encoding = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
//NSData* data = [string dataUsingEncoding:encoding];
//NSInteger length = [data length];
//if (length > CharacterCount) {
//NSData *data1 = [data subdataWithRange:NSMakeRange(0, CharacterCount)];
//NSString *content = [[NSString alloc] initWithData:data1 encoding:encoding];//注意:当截取CharacterCount长度字符时把中文字符截断返回的content会是nil
//if (!content || content.length == 0) {
//data1 = [data subdataWithRange:NSMakeRange(0, CharacterCount - 1)];
//content = [[NSString alloc] initWithData:data1 encoding:encoding];
//}
//return content;
//}
//return nil;
if(string.length> CharacterCount) {
NSLog(@"超出字数上限");
_totalCharacterLabel.text=@"0";
return[stringsubstringToIndex:CharacterCount];
}else{
_totalCharacterLabel.text= [NSStringstringWithFormat:@"%ld",(long)(CharacterCount - string.length)];
}
returnnil;
}
#pragma mark- TouchDelegate
- (void)touchesBegan:(NSSet *)toucheswithEvent:(UIEvent *)event{
[self.viewendEditing:YES];
}
#pragma mark- UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
[self.viewendEditing:YES];
returnYES;
}
- (BOOL)textField:(UITextField *)textFieldshouldChangeCharactersInRange:(NSRange)rangereplacementString:(NSString*)string{
if([selfisInputRuleNotBlank:string] || [stringisEqualToString:@""]) {//当输入符合规则和退格键时允许改变输入框
returnYES;
}else{
NSLog(@"超出字数限制");
returnNO;
}
}
@end