1. 如何實現對UITextField ,UITextView等輸入框的 字數限制html
(1)首先,確定要 讓controller 實現 UITextFieldDelegate (針對UITextField)或者 UITextViewDelegate(針對UITextView)函數
而後,將 輸入框的delegate屬性設置爲self. post
(2) 而後,咱們就能夠用這兩個delegate的函數來實現 咱們對輸入字數的限制了。spa
對於 UITextField 是函數.net
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string;htm
或者blog
對於UITextView 是函數rem
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text;get
若是容許繼續輸入,那麼返回YES,不然返回NO。string
代碼以下:
2. 如何實現 對有輸入限制的輸入框的剩餘字數的自動計算
好比上面的代碼中,輸入框的字數不能超過100,如何實時的計算出當前能夠輸入多少個字符呢?
UITextField 沒有找到合適的函數,也能夠在函數
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string;
中來實現。
代碼:
UITextView 除了能夠在函數
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
中按照上面相似的辦法處理之外,還能夠在函數
- (void)textViewDidChange:(UITextView *)textView 中處理。
代碼以下: