关于textField限制字数

在项目中有时候会输入Textfield 但是有交互需求 限制一定文字长度。

textField的代理方法

@protocol UITextFieldDelegate 

@optional

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField;        // return NO to disallow editing.
- (void)textFieldDidBeginEditing:(UITextField *)textField;           // became first responder
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField;          // return YES to allow editing to stop and to resign first responder status. NO to disallow the editing session to end
- (void)textFieldDidEndEditing:(UITextField *)textField;             // may be called if forced even if shouldEndEditing returns NO (e.g. view removed from window) or endEditing:YES called
- (void)textFieldDidEndEditing:(UITextField *)textField reason:(UITextFieldDidEndEditingReason)reason NS_AVAILABLE_IOS(10_0); // if implemented, called in place of textFieldDidEndEditing:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string;   // return NO to not change text

- (BOOL)textFieldShouldClear:(UITextField *)textField;               // called when clear button pressed. return NO to ignore (no notifications)
- (BOOL)textFieldShouldReturn:(UITextField *)textField;              // called when 'return' key pressed. return NO to ignore.

首先你可以利用

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string;   // return NO to not change text

这个方法来限制。举个例子。我需要限定50长度的字符。

NSString *toBeString = [textField.text stringByReplacingCharactersInRange:range withString:string];


        if (toBeString.length > INPUTMAXLENTH && range.length != 1  ) {
        textField.text = [toBeString substringToIndex:INPUTMAXLENTH];
        [[TipView sharedInstance] showMessage:@"最多输入50个字"];
        return NO;
    }
    return YES;

当你返回YES 才会成功。返回NO 就不会显示。

textField的通知

但是你发现 如果点智能添加的话。这样 就会限制不住了。所以还需要有一个方法。


UIKIT_EXTERN NSNotificationName const UITextFieldTextDidBeginEditingNotification;
UIKIT_EXTERN NSNotificationName const UITextFieldTextDidEndEditingNotification;
UIKIT_EXTERN NSNotificationName const UITextFieldTextDidChangeNotification;

他还有三个通知。
调用利用didChangeNotification通知来限制字符。


[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(textFieldEditChange:) name:@"UITextFieldTextDidChangeNotification" object:self.orderTimeText];

然后调用方法把你的textfield传过来
- (void)textFieldEditChange:(NSNotification *)notify{
      UITextField *textField = notify.object;
    NSString * toBeString = textField.text;
    if (toBeString.length > INPUTMAXLENTH) {
        [[TipView sharedInstance] showMessage:@"最多输入50个字"];
        textField.text = [toBeString substringToIndex:INPUTMAXLENTH];
    }else{
        textField.text = toBeString;
    }
}

这样的话 就会限制住了。~~~
但是提醒一下 使用通知后 不要忘记移除哦。

你可能感兴趣的:(关于textField限制字数)