您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 教學 >> iOS 相關教學

限制 TextField 與 TextView 輸入字數的做法

編輯:iOS 相關教學

表單驗證裡最常見的需求之一,就是限制輸入長度。UITextField 與 UITextView 都提供了 shouldChange 系列的 delegate 方法,只要在其中判斷「改動後的長度」是否超標即可。以下分享具體實作,供大家參考。

TextField 的作法是

在 textField:shouldChangeCharactersInRange:replacementString: 裡計算改動後的總長度,超過上限就回傳 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;
    // 超過 16 字就不能再輸入
    if (pointLength > 16) {
        return NO;
    } else {
        return YES;
    }
}

關鍵在於要扣掉被選取(即將被取代)的長度,否則使用者選取幾個字重新輸入時會被誤判為超長。

TextView 的作法是

- (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;
}

這裡順手把「按 return 收起鍵盤」一起處理了。另外要注意,上面的寫法把 range 的替換情境簡化了;如果你的輸入框允許選取部分文字覆寫,建議比照 TextField 的算法把 selectedLength 一併扣除,準確度會更好。若還需要顯示剩餘字數提示,可以在 shouldChange 中同步更新提示 label,或者在 textViewDidChange: 裡統一刷新。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved