限制输入框输入长度
[TextFiled addTarget:self action:@selector(textfieldDidChange:) forControlEvents:UIControlEventEditingChanged];
[self.TextField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
-(void)textFieldDidChange:(UITextField *)textField
{
NSUInteger maxLength =11;
NSString*toBeString = textField.text;
//获取高亮部分
UITextRange*selectedRange = [textFieldmarkedTextRange];
UITextPosition*position = [textFieldpositionFromPosition:selectedRange.startoffset:0];
if(!position || !selectedRange)
{
if(toBeString.length> maxLength)
{
NSRangerangeIndex = [toBeStringrangeOfComposedCharacterSequenceAtIndex:maxLength];
if(rangeIndex.length==1)
{
textField.text= [toBeStringsubstringToIndex:maxLength];
}
else
{
NSRangerangeRange = [toBeStringrangeOfComposedCharacterSequencesForRange:NSMakeRange(0, maxLength)];
textField.text= [toBeStringsubstringWithRange:rangeRange];
}
}
}
}
限制输入框输入内容
//数字
#define NUM @"0123456789"
//字母
#define ALPHA @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
//数字和字母
#define ALPHANUM @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
#pragma mark -- UITextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
//数字和字母
NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:ALPHANUM] invertedSet];
//数字
//NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:NUM] invertedSet];
//字母
//NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:ALPHA] invertedSet];
NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
return[stringisEqualToString:filtered];
}
网友评论