一、限制字数输入的方法
1.在UITextFieldDelegate的代理方法中可以限制输入
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if (textField == self.TextField) {
if (string.length == 0) return YES;
NSInteger existedLength = textField.text.length;
NSInteger selectedLength = range.length;
NSInteger replaceLength = string.length;
if (existedLength - selectedLength + replaceLength > 11) {
return NO;
}
}
}
return YES;
}
还可以在其中截取请11个字
if (textField == TextFeild) {
NSInteger existedLength = textField.text.length;
NSInteger selectedLength = range.length;
NSInteger replaceLength = string.length;
NSString *nameString = [NSString stringWithFormat:@"%@%@",textField.text,string];
if (existedLength - selectedLength + replaceLength > 11) {
textField.text = [nameString substringToIndex:11];
return NO;
}
}
2.同样的方法,在textview的- (void)textViewDidChange:(UITextView *)textView;中也可以限制字数输入
- (void)textViewDidChange:(UITextView *)textView{
if (textField == _phoneNumberTextFeild) {
CGFloat maxLength = 11;
NSString *toBeString = textField.text;
//获取高亮部分
UITextRange *selectedRange = [textField markedTextRange];
UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
if (!position || !selectedRange)
{
if (toBeString.length > maxLength)
{
NSRange rangeIndex = [toBeString rangeOfComposedCharacterSequenceAtIndex:maxLength];
textField.text = [toBeString substringToIndex:11];
}
}
}
}
这是两种比较简单的方法,大家可以使用
二、对输入框高亮部分的处理
1.避免高亮状态触发限制字数
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
UITextRange *selectedRange = [textView markedTextRange];
NSString *newText = [textView textInRange:selectedRange]; //获取高亮部分
if (newText.length>0 && textView == _leaveTextView) {
return YES;
}
return YES;
}
2.输入结束后对输入框处理
- (void)textViewDidChange:(UITextView *)textView {
UITextRange *selectedRange = [textView markedTextRange];
NSString *newText = [textView textInRange:selectedRange]; //获取高亮部分
if (newText.length>0 && textView == _TextView) {
_leavePlaceLabel.hidden = YES;
} else {
// 限制最大字数
if (textView.text.length > 120) {
textView.text = [string substringToIndex:120];
[WDAlert showAlertWithMessage:@"最多输入120字" time:1.0];
}
}
if (textView == _leaveTextView) {
if ([textView.text isEqualToString:@""]) {
_placeLabel.hidden = NO;
} else {
_placeLabel.hidden = YES;
}
}
三、截取字符串时,对表情符号截取的处理
使用substringToIndex进行字符串截取,这样做有一个潜在的问题,那就是当截取的index恰好是一个表情符号的时候,因为一个emoij在字符串的length并不等于1,这样就会把表情符号分割开来,从而造成整个字符串不显示或者最后一个字符是乱码。一半的emoji的时候,把字符串进行UTF8String转码后为NULL。
所以截取时需要判断表情符号的位置
-(NSString *)subStringWith:(NSString *)string ToIndex:(NSInteger)index{
NSString *result = string;
if (result.length > index) {
NSRange rangeIndex = [result rangeOfComposedCharacterSequenceAtIndex:index];
result = [result substringToIndex:(rangeIndex.location)];
}
return result;
}
此时就可以截取到正确的字符串了。