IOS中UITextView或UITextField字?jǐn)?shù)限制的實(shí)現(xiàn)
UITextView或UITextField字?jǐn)?shù)限制,輸入時(shí)的限制,復(fù)制粘貼時(shí)的限制
字?jǐn)?shù)限制有三種方法
在代理方法
“- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string”
或
“- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text”
中實(shí)現(xiàn)兩種方法
方法1(只能在輸入時(shí)限制,復(fù)制粘貼時(shí)無(wú)法限制)
if (range.location > MaxCharacterNumber - 1){ textField.text = [textField.text substringToIndex:MaxCharacterNumber]; return NO;}
方法2(輸入及復(fù)制粘貼時(shí)均可限制)
NSString *temp = [textField.text stringByReplacingCharactersInRange:range withString:string];if (temp.length > MaxCharacterNumber){ textField.text = [temp substringToIndex:MaxCharacterNumber]; return NO;}
在代理方法
“- (void)textViewDidChange:(UITextView *)textView”
中實(shí)現(xiàn)一種方法
方法3(復(fù)制粘貼時(shí)均可限制)
NSString *textString = textView.text;if (textString.length > MaxCharacterNumbers + 1){ textView.text = [textString substringToIndex:MaxCharacterNumbers]; return;}
注意:
“NSString *temp = [textField.text stringByReplacingCharactersInRange:range withString:string];”
為字符范圍替換為指定的字符串,返回新的字符串。
如有疑問(wèn)請(qǐng)留言或者到本站社區(qū)交流討論,感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!
新聞熱點(diǎn)
疑難解答
圖片精選