当前位置: 代码迷 >> 综合 >> IOS UITextView 和 UITextField 联想输入法字数限制
  详细解决方案

IOS UITextView 和 UITextField 联想输入法字数限制

热度:93   发布时间:2023-12-15 02:05:16.0

UITextField  输入限制

  [_tfTextFeild addTarget:self action:@selector(limitLength:) forControlEvents:UIControlEventEditingChanged];

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{if (textField == _tfTextFeild){if (string.length == 0) return YES;NSInteger existedLength = textField.text.length;NSInteger selectedLength = range.length;NSInteger replaceLength = string.length;if (existedLength - selectedLength + replaceLength > TEXT_MAXLENGTH){return NO;}}return YES;
}- (void)limitLength:(UITextField *)textField
{if (textField == _tfTextFeild){if (textField.text.length > TEXT_MAXLENGTH){textField.text = [textField.text substringToIndex:TEXT_MAXLENGTH];}}
}

UITextView输入限制

 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textViewEditChanged) name:UITextViewTextDidChangeNotification object:nil];

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{if (textView == _contentTextView){if (text.length == 0) return YES;NSInteger existedLength = textView.text.length;NSInteger selectedLength = range.length;NSInteger replaceLength = text.length;if (existedLength - selectedLength + replaceLength > TEXT_MAXLENGTH){return NO;}}return YES;
}- (void)textViewEditChanged
{if (_contentTextView.text.length > TEXT_MAXLENGTH){_contentTextView.text = [_contentTextView.text substringToIndex:TEXT_MAXLENGTH];}
}


  相关解决方案