現(xiàn)在的服務器一般是不會對字數(shù)做限制的,但是遇到一個需求需要對字數(shù)做限制,并且同時更新剩余的字數(shù),也許有些朋友會想著用textField或label來做,單是總是存在一些不完美,或一些其他的問題難解決.

用textField的話,自動換行是個難題,因為他并不提供這個屬性.用textView則可以和容易解決,因為textView默認有自動換行這個功能.
實現(xiàn)代碼入下:
在viewDidLoad添加方法(記得別忘了順手添加移除)
//? ? 添加監(jiān)聽方法
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(textViewDidChange:) name:UITextViewTextDidChangeNotification object:nil];
監(jiān)聽方法的實現(xiàn)
#pragma mark - 當textField布局發(fā)生改變的時候調(diào)用
- (void)textViewDidChange:(UITextView *)textView {
//? ? 對占位符的顯示和隱藏做判斷
if (self.textViewLength.text .length == 0) {
self.ploLabel.text =? @"請輸反饋信息";
}else {
self.ploLabel.text = @"";
}
//? ? 讀出textView字符長度
self.wordLabelCount.text = [NSString stringWithFormat:@"%lu",200 - self.textViewLength.text .length];
if (self.textViewLength.text .length > 200) {
//? ? ? ? 對超出的部分進行剪切
self.textViewLength.text = [self.textViewLength.text substringToIndex:10];
self.wordLabelCount.text = @"0";
}
if (self.textViewLength.text .length >= 200) {
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"溫馨提示!" message:@"親!最多只能輸入200個字!請您合理安排內(nèi)容!" preferredStyle:UIAlertControllerStyleAlert];
[self presentViewController:alertController animated:YES completion:nil];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[self dismissViewControllerAnimated:YES completion:nil];
? ? ? ?});
?}
}
#pragma mark - 移除監(jiān)聽方法
- (void)dealloc {
[[NSNotificationCenter defaultCenter]removeObserver:self];
}
這里有一個細節(jié)就是將超出的文字給cut掉,就是用到這個方法: ? ??
?對超出的部分進行剪切
self.textViewLength.text = [self.textViewLength.text substringToIndex:10];
并且這個時候要讓跟新的數(shù)字一直是0
self.wordLabelCount.text = @"0";
為了更好的用戶體驗,添加提示占位符是必要的,我在這里也做了,順便連帶的說一下,這樣才算完整嗎.就在上面得代碼中:
//? ? 對占位符的顯示和隱藏做判斷
if (self.textViewLength.text .length == 0) {
self.ploLabel.text =? @"請輸反饋信息";
}else {
self.ploLabel.text = @"";
}
最后我想說一句:
我很欣賞喬布斯的一句話 ---- 用戶體驗至上!