透過 shouldChangeCharactersInRange: 這個 delegate 方法,在字串變更前先計算「變更後的總長度」,超過上限就回傳 NO 拒絕本次輸入。以下範例把上限設為 16,可依需求調整:
- (BOOL)textField:(UITextField *)textField
shouldChangeCharactersInRange:(NSRange)range
replacementString:(NSString *)string {
NSInteger existedLength = textField.text.length; // 目前長度
NSInteger selectedLength = range.length; // 被選取(即將刪除)的長度
NSInteger replaceLength = string.length; // 即將插入的長度
NSInteger pointLength = existedLength - selectedLength + replaceLength;
if (pointLength > 16) return NO; // 超過 16 字元則拒絕
return YES;
}
這段計算很重要:如果只寫 textField.text.length + string.length > 16,那麼當使用者在中間選取幾個字重新輸入時,就會被誤判為超長。
- (BOOL)textView:(UITextView *)textView
shouldChangeTextInRange:(NSRange)range
replacementText:(NSString *)text {
// 換行時收起鍵盤(等同 textField 按下 return 的效果)
if ([text isEqualToString:@"\n"]) {
[textView resignFirstResponder];
return NO;
}
// 判斷加上本次輸入後是否超過上限
NSString *str = [NSString stringWithFormat:@"%@%@", textView.text, text];
if (str.length > 500) {
textView.text = [textView.text substringToIndex:500];
return NO;
}
return YES;
}
textView.text 截斷,這會觸發一次副作用(游標位置可能跳到頭部、undo 記錄被污染)。更乾淨的做法與 TextField 一致,一律回傳 NO:
NSInteger finalLength = textView.text.length - range.length + text.length; return finalLength <= 500;
NSString.length(UTF-16 碼元數)會把 emoji 算成 2。此類需求應改用 count 於 Swift 或 [str length] 搭配 grapheme cluster 的計算方式。限制字數看起來是瑣事,但「用 range 精確計算」與「以回傳 NO 取代直接改寫 text」這兩點,能避免絕大多數游標跳動與內容錯亂的問題。若有疑問歡迎留言討論。