2015-01-14 5 views
0

사용자가 전화 번호를 입력해야하는 UITextField가 있습니다.UITextField 시작 부분에 상수 국가 코드 추가하기

이것은 지금과 같은 모습입니다 :

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string 
{ 
    // Auto-add hyphen before appending 4rd or 7th digit 
    // 
    // 
    if (range.length == 0 && (range.location == 3 || range.location == 7)) 
    { 
     textField.text = [NSString stringWithFormat:@"%@-%@", textField.text, string]; 
     return NO; 
    } 

    // Delete hyphen when deleting its trailing digit 
    // 
    // 
    if (range.length == 1 && (range.location == 4 || range.location == 8)) 
    { 
     range.location--; 
     range.length = 2; 
     textField.text = [textField.text stringByReplacingCharactersInRange:range withString:@""]; 
     return NO; 
    } 

    // Prevent crashing undo bug – see note below. 
    // 
    // 
    if (range.length + range.location > textField.text.length) 
    { 
     return NO; 
    } 

    // Limit text field characters 
    // 
    // 
    NSUInteger newLength = [textField.text length] + [string length] - range.length; 
    return (newLength > 12) ? NO : YES; 
} 

는 3 자리 숫자 후, 하이픈을 추가하고 다시보다하고 있습니다. 여기서 달성하고자하는 것은 UITextField 시작 부분에 국가 코드를 상수로 추가하고 사용자가이를 제거하지 못하도록하는 것입니다. 미국 국가 코드를 말할 수 다음 UITextField 텍스트가 시작 +1-에서 그 모양을 한 다음 전체 수를 작성 후에는 다음과 같이 표시됩니다 +1-600-242-252

내가 어떻게 할 수 있습니까?

미리 감사드립니다.

답변

-1

처음에 상수를 유지하려면 기본적으로 상수가 제안 된 텍스트에 여전히 존재하는지 확인해야합니다. 그러한 편집을 거부하지 않는 경우.

특정 편집 단계에서 하이픈을 삽입하지 마십시오. 전체 문자열을 조작하는 것이 좋습니다.

예.

  1. 문자열이 유효 할 수 있는지 테스트합니다.

    - (void)viewDidLoad { 
        [super viewDidLoad]; 
        self.textField.text = @"+1"; // start with a +1 in the textField otherwise we can't change the field at all 
    } 
    
    - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { 
        NSString *proposedText = [textField.text stringByReplacingCharactersInRange:range withString:string]; 
    
        if (![proposedText hasPrefix:@"+1"]) { 
         // tried to remove the first +1 
         return NO; 
        } 
        NSString *formattedPhoneNumber = [proposedText substringFromIndex:2]; // without +1 prefix 
        NSString *unformattedPhoneNumber = [formattedPhoneNumber stringByReplacingOccurrencesOfString:@"-" withString:@""]; // without hypens 
    
        // start with the prefix 
        NSMutableString *newText = [NSMutableString stringWithString:@"+1"]; 
    
        for (NSInteger i = 0; i < [unformattedPhoneNumber length]; i++) { 
         if (i % 3 == 0) { 
          // add a - every 3 characters. add one at the beginning as well 
          [newText appendString:@"-"]; 
         } 
         // add each digit from the unformatted phonenumber 
         [newText appendString:[unformattedPhoneNumber substringWithRange:NSMakeRange(i, 1)]]; 
        } 
        textField.text = newText; 
        return NO; 
    } 
    

    이 여전히 매우 순진 구현입니다 : 즉 starts with +1

  2. 제거 모든 하이픈 이전에
  3. 다시 삽입이 같을 것이다 코드에서 모든 하이픈

을 추가했다. 몇 가지 문제가 있습니다. 예를 들어, 커서를 항상 textField의 text을 수동으로 설정했기 때문에 항상 끝나야합니다. 따라서 사용자는 문자열 중간에있는 숫자를 쉽게 제거 할 수 없습니다. 물론이 문제를 해결하는 방법이 있습니다. selectedTextRange은 사용할 속성입니다. 전화 번호를 필드에 붙여 넣을 수는 없습니다. 물론 사용자는 하이픈을 삭제할 수 없습니다.

사용자가 입력하는 동안 서식이 너무 많은 가장자리 경우가 있기 때문에 빠르게 복잡 해지는 경향이 있습니다. 하지만 그렇게하면 시작할 수 있습니다.

+0

마지막 그룹화는 연속 4 개의 숫자입니다. 현재 코드에서는 해당 숫자를 잘못 그룹화합니다 (예 :+ 1-675-973-874-2. 또한 그것을 아직 처리하지 않았기 때문에 그것은 12 자리에서 멈추지 않을 것입니다 ... –

+0

그리고 selectedTextRange는 UITextViews에만 해당합니다. –

0

이 대답은 끝 부분에 하이픈을 포함하는 시작 국가 코드 문자열 (예 : self.countryCode = @"+1-";)을 가정합니다. 텍스트 필드는 기본적으로 "+ 1"을 포함해야합니다.

간과 한 많은 사용 사례 (예 : 여러 문자로 복사하여 붙여 넣기 작업, 부적절한 하이픈 삭제, 부적절한 하이픈 추가, 중간 선 삽입 등)을 처리하기 때문에 원래 의도보다 포괄적 인 답변을 만들었습니다. 등등. 당신의 원래 대답이 어떤면에서는 비특이적이기 때문에 여전히 완벽하지는 않습니다. 예를 들어, 사용자가 숫자 만 입력 할 수 있도록 지정하면 코드가 훨씬 깔끔해질 수 있습니다.

아래의 구현은 전체적으로 포함 된 설명에서 한 줄씩 설명합니다.

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string 
{ 
    // Combine the new text with the old 
    NSMutableString *combinedText = [[textField.text stringByReplacingCharactersInRange:range withString:[NSString stringWithFormat:@"%@", string]] mutableCopy]; 

    // If the user deletes part of the country code or tries 
    // to edit it in any way, don't allow it 
    if (combinedText.length < self.countryCode.length || 
     ![combinedText hasPrefix:self.countryCode]) { 
     return NO; 
    } 

    // Limit text field characters to 12 
    if (combinedText.length > self.countryCode.length + 12) { 
     return NO; 
    } 

    // If the user tries to add a hyphen where there's supposed 
    // to be a hyphen, allow them to do so. 
    if ([string isEqualToString:@"-"] && 
     (range.location == self.countryCode.length + 3 || 
     range.location == self.countryCode.length + 7)) { 
     return YES; 
    } 

    // Remove all the hyphens other than the one directly 
    // following the country code   
    [combinedText replaceOccurrencesOfString:@"-" withString:@"" options:0 range:NSMakeRange(self.countryCode.length, [combinedText length] - self.countryCode.length)]; 

    // Auto-add the hyphens before the 4th and 7th digits 
    if (combinedText.length > self.countryCode.length + 3) 
     [combinedText insertString:@"-" atIndex:self.countryCode.length + 3]; 
    if (combinedText.length > self.countryCode.length + 7) 
     [combinedText insertString:@"-" atIndex:self.countryCode.length + 7]; 

    // Store the original cursor position 
    UITextPosition *pos = [textField selectedTextRange].start; 

    // Count up the original number of hyphens 
    NSUInteger originalNumberOfHyphens = [[textField.text componentsSeparatedByString:@"-"] count] - 1; 
    // Count up the new number of hyphens 
    NSUInteger newNumberOfHyphens = [[combinedText componentsSeparatedByString:@"-"] count] - 1; 

    // Create a cursor offset to reflect the difference 
    // in the number of hyphens 
    float offset = newNumberOfHyphens - originalNumberOfHyphens; 

    // Update the text field to contain the combined text 
    textField.text = combinedText; 

    // Update the cursor position appropriately 
    if (string.length > 0) { 
     UITextPosition* cursor = [textField positionFromPosition:[textField beginningOfDocument] offset:range.location + range.length + offset + string.length]; 
     textField.selectedTextRange = [textField textRangeFromPosition:cursor toPosition:cursor]; 
    } else { 
     UITextPosition* cursor = [textField positionFromPosition:pos inDirection:UITextLayoutDirectionLeft offset:1-offset]; 
     textField.selectedTextRange = [textField textRangeFromPosition:cursor toPosition:cursor]; 
    } 

    // No need to replace the string since it's already been done 
    return NO; 
} 
+0

그것은 2 characts + 국가 코드 –

+0

으로 제한됩니다. @JesseOnolememen 방금이 코드를 다시 테스트했고 그것은 나를 위해 일합니다 .... 당신이 의미하는 바를 설명해주십시오. "단지 2 문자 + 국가 코드로 제한됩니다" –

+1

처음에는 국가 코드와 함께 2 자만 입력 할 수있었습니다. 나는 신속하게 문제를 일으킨 변환 과정에서 오류가 발생했습니다. 이제 완벽하게 작동합니다. @lyndsetscott –

관련 문제