- 字母数字 textfield、delegate
-
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string;
{
//string就是此时输入的那个字符 textField就是此时正在输入的那个输入框 返回YES就是可以改变输入框的值 NO相反
if ([string isEqualToString:@" "]) //按会车可以改变
{
return YES;
}
NSString * toBeString = [textField.text stringByReplacingCharactersInRange:range withString:string]; //得到输入框的内容
if (_nameField == textField) //判断是否时我们想要限定的那个输入框
{
NSInteger lengyh=[toBeString length];
NSLog(@"=length==%zd",lengyh);
if (lengyh > 20) { //如果输入框内容大于20则弹出警告
textField.text = [textField.text substringToIndex:20];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"不能超过20位哦!" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
[alert show];
return NO;
}
}
return YES;
}
- 有汉字的
-
#define MAX_STARWORDS_LENGTH 20
防在 viewdid 中
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(textFieldEditChanged:)
name:@"UITextFieldTextDidChangeNotification" object:_nameField];
-
#pragma mark - Notification Method
-(void)textFieldEditChanged:(NSNotification *)obj
{
UITextField *textField = (UITextField *)obj.object;
NSString *toBeString = textField.text;
NSString *lang = [textField.textInputMode primaryLanguage];
if ([lang isEqualToString:@"zh-Hans"])// 简体中文输入
{
//获取高亮部分
UITextRange *selectedRange = [textField markedTextRange];
UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
// 没有高亮选择的字,则对已输入的文字进行字数统计和限制
if (!position)
{
if (toBeString.length > MAX_STARWORDS_LENGTH)
{
textField.text = [toBeString substringToIndex:MAX_STARWORDS_LENGTH];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"不能超过20位哦!" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
[alert show];
}
}
}
// 中文输入法以外的直接对其统计限制即可,不考虑其他语种情况
else
{
if (toBeString.length > MAX_STARWORDS_LENGTH)
{
NSRange rangeIndex = [toBeString rangeOfComposedCharacterSequenceAtIndex:MAX_STARWORDS_LENGTH];
if (rangeIndex.length == 1)
{
textField.text = [toBeString substringToIndex:MAX_STARWORDS_LENGTH];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"不能超过20位哦!" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
[alert show];
}
else
{
NSRange rangeRange = [toBeString rangeOfComposedCharacterSequencesForRange:NSMakeRange(0, MAX_STARWORDS_LENGTH)];
textField.text = [toBeString substringWithRange:rangeRange];
NSLog(@"201");
}
}
}
}
-(void)dealloc{
[[NSNotificationCenter defaultCenter] removeObserver:self];
[[NSNotificationCenter defaultCenter]removeObserver:self
name:@"UITextFieldTextDidChangeNotification"
object:_nameField];
}
-