iOS 限制textField輸入的長度

碼鋒窩發表於2016-12-15

1.電話號碼(帶3-3-4效果)

  1. //指定代理
      
     self.phoneTextField.delegate = self;

  2.  
       //當編輯改變的時候,進行字元校驗
        [self.phoneTextField addTarget:self action:@selector(reformatAsPhoneNumber:) forControlEvents:UIControlEventEditingChanged];
    

  3. #pragma mark - 手機號碼分隔
    /**
     *  3-3-4手機號碼分隔
     */
    -(void)reformatAsPhoneNumber:(UITextField *)textField {
        //判斷正確的游標位置
        NSUInteger targetCursorPostion = [textField offsetFromPosition:textField.beginningOfDocument toPosition:textField.selectedTextRange.start];
        NSString *phoneNumberWithoutSpaces = [self removeNonDigits:textField.text andPreserveCursorPosition:&targetCursorPostion];
        if([phoneNumberWithoutSpaces length] > 11) {
            //避免超過11位的輸入
            [textField setText:_previousTextFieldContent];
            textField.selectedTextRange = _previousSelection;
            return;
        }
    
        NSString *phoneNumberWithSpaces = [self insertSpacesEveryFourDigitsIntoString:phoneNumberWithoutSpaces andPreserveCursorPosition:&targetCursorPostion];
    
        textField.text = phoneNumberWithSpaces;
        UITextPosition *targetPostion = [textField positionFromPosition:textField.beginningOfDocument offset:targetCursorPostion];
        [textField setSelectedTextRange:[textField textRangeFromPosition:targetPostion toPosition:targetPostion]];
    }
    
    /**
     *  除去非數字字元,確定游標正確位置
     *
     *  @param string         當前的string
     *  @param cursorPosition 游標位置
     *
     *  @return 處理過後的string
     */
    - (NSString *)removeNonDigits:(NSString *)string andPreserveCursorPosition:(NSUInteger *)cursorPosition {
        NSUInteger originalCursorPosition = *cursorPosition;
        NSMutableString *digitsOnlyString = [NSMutableString new];
    
        for (NSUInteger i=0; i<string.length; i++) {
            unichar characterToAdd = [string characterAtIndex:i];
    
            if(isdigit(characterToAdd)) {
                NSString *stringToAdd = [NSString stringWithCharacters:&characterToAdd length:1];
                [digitsOnlyString appendString:stringToAdd];
            }
            else {
                if(i<originalCursorPosition) {
                    (*cursorPosition)--;
                }
            }
        }
        return digitsOnlyString;
    }
    
    /**
     *  將空格插入我們現在的string 中,並確定我們游標的正確位置,防止在空格中
     *
     *  @param string         當前的string
     *  @param cursorPosition 游標位置
     *
     *  @return 處理後有空格的string
     */
    - (NSString *)insertSpacesEveryFourDigitsIntoString:(NSString *)string andPreserveCursorPosition:(NSUInteger *)cursorPosition{
        NSMutableString *stringWithAddedSpaces = [NSMutableString new];
        NSUInteger cursorPositionInSpacelessString = *cursorPosition;
    
        for (NSUInteger i=0; i<string.length; i++) {
            if(i>0){
                if(i==3 || i==7) {
                    [stringWithAddedSpaces appendString:@" "];
                    if(i<cursorPositionInSpacelessString) {
                        (*cursorPosition)++;
                    }
                }
            }
            unichar characterToAdd = [string characterAtIndex:i];
            NSString *stringToAdd = [NSString stringWithCharacters:&characterToAdd length:1];
            [stringWithAddedSpaces appendString:stringToAdd];
        }
        return stringWithAddedSpaces;
    }
    
    #pragma mark - UITextFieldDelegate
    
    -(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
        _previousSelection = textField.selectedTextRange;
        _previousTextFieldContent = textField.text;
        if ( textField == self.phoneHMDTextField &&range.location >= 11){
            return  NO;
        }else {
            return YES;
        }
    }
    

     

二:監聽代理方法(這樣可以在if裡通過判斷,做幾個textfield的限制輸入)

 

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {

    if ( textField == self.phoneHMDTextField  && range.location >= 11){
        return  NO;
    }else {
        return YES;
    }
}

 

三:

 

  //指定代理

    self.phoneTextField.delegate = self;

    //當編輯改變的時候,進行字元校驗

    [self.phoneTextField addTarget:self action:@selector(reformatAsPhoneNumber:) forControlEvents:UIControlEventEditingChanged];

//監聽字元改變的方法

- (void)textFieldDidChange:(UITextField *)textField
{
    if (textField == self.textFieldName) {
        if (textField.text.length > 15) {
        UITextRange *markedRange = [textField markedTextRange];
           if (markedRange) {
              return;
           }
            //Emoji佔2個字元,如果是超出了半個Emoji,用15位置來擷取會出現Emoji截為2半
        //超出最大長度的那個字元序列(Emoji算一個字元序列)的range
        NSRange range = [textField.text rangeOfComposedCharacterSequenceAtIndex:15];
            textField.text = [textField.text substringToIndex:range.location];
        }
    }
}

 

相關文章