IOS中UITextView或UITextField字數(shù)限制的實現(xiàn)
更新時間:2017年10月11日 09:29:10 投稿:lqh
這篇文章主要介紹了IOS中UITextView或UITextField字數(shù)限制的實現(xiàn)的相關資料,希望通過本文能幫助到大家實現(xiàn)這樣的功能,需要的朋友可以參考下
IOS中UITextView或UITextField字數(shù)限制的實現(xiàn)
UITextView或UITextField字數(shù)限制,輸入時的限制,復制粘貼時的限制
字數(shù)限制有三種方法
在代理方法
“- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string”
或
“- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text”
中實現(xiàn)兩種方法
方法1(只能在輸入時限制,復制粘貼時無法限制)
if (range.location > MaxCharacterNumber - 1) { textField.text = [textField.text substringToIndex:MaxCharacterNumber]; return NO; }
方法2(輸入及復制粘貼時均可限制)
NSString *temp = [textField.text stringByReplacingCharactersInRange:range withString:string]; if (temp.length > MaxCharacterNumber) { textField.text = [temp substringToIndex:MaxCharacterNumber]; return NO; }
在代理方法
“- (void)textViewDidChange:(UITextView *)textView”
中實現(xiàn)一種方法
方法3(復制粘貼時均可限制)
NSString *textString = textView.text; if (textString.length > MaxCharacterNumbers + 1) { textView.text = [textString substringToIndex:MaxCharacterNumbers]; return; }
注意:
“NSString *temp = [textField.text stringByReplacingCharactersInRange:range withString:string];”
為字符范圍替換為指定的字符串,返回新的字符串。
如有疑問請留言或者到本站社區(qū)交流討論,感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
相關文章
iPhone/iPad開發(fā)通過LocalNotification實現(xiàn)iOS定時本地推送功能
這篇文章主要介紹了iPhone/iPad開發(fā)之通過LocalNotification實現(xiàn)iOS定時本地推送功能,具有一定的參考價值,感興趣的小伙伴們可以參考一下2016-09-09iOS定時器的選擇CADisplayLink NSTimer和GCD使用
這篇文章主要為大家介紹了iOS定時器的選擇CADisplayLink NSTimer和GCD使用詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-03-03