知识片段---textfield限制字符输入个数(包括汉子)

悠悠 2022-08-20 02:27 211阅读 0赞

[[ NSNotificationCenter defaultCenter ] addObserver : self selector : @selector ( textFiledEditChanged :)
name : @”UITextFieldTextDidChangeNotification”

  1. object:self.nameField\];

/**
* 限制名字输入字符的个数
*
* @param obj <#obj description#>
*/
-( void )textFiledEditChanged:( NSNotification *) obj {
UITextField * textField = ( UITextField *) obj . object ;

  1. NSString \* toBeString = textField . text ;
  2. NSString \* lang = \[\[ UITextInputMode currentInputMode \] primaryLanguage \]; // 键盘输入模式
  3. if (\[ lang isEqualToString : @"zh-Hans" \]) \{ // 简体中文输入,包括简体拼音,健体五笔,简体手写
  4. UITextRange \* selectedRange = \[ textField markedTextRange \];
  5. // 获取高亮部分
  6. UITextPosition \* position = \[ textField positionFromPosition : selectedRange . start offset :0\];
  7. // 没有高亮选择的字,则对已输入的文字进行字数统计和限制
  8. if (! position ) \{
  9. if ( toBeString . length > 8) \{
  10. textField . text = \[ toBeString substringToIndex :8\];
  11. \}
  12. \}
  13. // 有高亮选择的字符串,则暂不对文字进行统计和限制
  14. else \{
  15. \}
  16. \}
  17. // 中文输入法以外的直接对其统计限制即可,不考虑其他语种情况
  18. else \{
  19. if ( toBeString . length > 8) \{
  20. textField . text = \[ toBeString substringToIndex :8\];
  21. \}
  22. \}

}

发表评论

表情:
评论列表 (有 0 条评论,211人围观)

还没有评论,来说两句吧...

相关阅读