ios开发之UITextField、UITextView限制最大输入数
程序员文章站
2024-01-01 13:09:04
UITextField
不多说直接上代码
首先定一个全局常量maxNum, 指定一个最大输入范围
NSInteger const maxNum = 20;
创建一个UI...
UITextField
不多说直接上代码
首先定一个全局常量maxNum, 指定一个最大输入范围NSInteger const maxNum = 20;创建一个UITextField对像,为你的UITextField对象添加监听方法
[self.textField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];实现TextField的监听方法
#pragma mark -------UITextFiledDelegate -(void)textFieldDidChange:(UITextField *)textField { NSString *toBeString = textField.text; //获取高亮部分 UITextRange *selectedRange = [textField markedTextRange]; UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0]; if (!position || !selectedRange) { if (toBeString.length > maxNum) { NSRange rangeIndex = [toBeString rangeOfComposedCharacterSequenceAtIndex:maxNum]; if (rangeIndex.length == 1) { textField.text = [toBeString substringToIndex:maxNum]; } else { NSRange rangeRange = [toBeString rangeOfComposedCharacterSequencesForRange:NSMakeRange(0, maxNum)]; textField.text = [toBeString substringWithRange:rangeRange]; } } } }
UITextView
首定以一个全局常量NSInteger const maxNum = 20;创建一个UITextView对象并实现它的监听代理方法
#pragma mark ------- UITextViewDelegate - (void)textViewDidChange:(UITextView *)textView { if (textView.text.length >= maxDetailNum) { textView.text = [textView.text substringToIndex:maxDetailNum]; } }