본문 바로가기
iOS/iOS

UITextField

by 패쓰킴 2022. 11. 28.
728x90

자동입력

문자 인증 시 키보드 위에 인증번호가 뜨고 

눌렀을 때 입력창에 바로 입력이 되는 기능

 

TextField 창의 content typeOne TIme Code로 설정만 하면 끝

 

간단하게 테스트 하는 방법은

 

인증을 받을 핸드폰으로 다른 핸드폰에서 문자를 전송해보면 된다

단, 문자의 내용은 반드시

"인증번호 + (, : 는)등의 조사 + 0000"

와 같은 형식이어야 한다

 

참고 : https://swieeft.github.io/2020/08/13/MobileAuthNumberAutomaticCompletion.html

 

TextField 휴대폰 인증번호 자동완성 기능 구현하기 - 뀔뀔(swieeft)의 개발새발기

안녕하세요. 오늘은 간단한 포스팅이 될 것 같은데요. iOS 12부터는 문자인증을 받을 때 인증 번호를 수신하면 문자 메시지에 가서 확인하지 않아도 키보드에 자동완성을 보여주는 기능을 제공해

swieeft.github.io

 

attributedPlaceholder

objective - c

UIColor * color = [Util getColor:176 g:190 b:197];
_personNameTF.attributedPlaceholder =
  [[NSAttributedString alloc] initWithString:@"이름 입력"
    attributes:@{
    NSForegroundColorAttributeName: color,
    NSFontAttributeName : [UIFont fontWithName:@"AppleSDGothicNeo-regular" size:16.0]
    }
  ];

 

swift

let emailAttributes = [
  NSAttributedString.Key.foregroundColor: UIColor(red: 110, green: 137, blue: 163, alpha: 1),
  NSAttributedString.Key.font : UIFont(name: "Pretendard-Regular", size: 18)!
  ]
 emailTextField.attributedPlaceholder = NSAttributedString(string: "이메일", attributes:emailAttributes)

 

hypen(-)

참고: https://stackoverflow.com/questions/37571247/how-to-add-hyphens-in-uitextfield-ios-swift

 

How to add Hyphens in UITextField iOS Swift?

Need the following format of Numbers with Hyphen when typing in UITextField.

stackoverflow.com

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    // All digits entered
    if range.location == 12 {
        return false
    }
    // Reject appending non-digit characters
    if range.length == 0 && !NSCharacterSet.decimalDigitCharacterSet().characterIsMember(string.characterAtIndex(0)) {
        return false
    }
    // Auto-add hyphen before appending 4rd or 7th digit
    if range.length == 0 && (range.location == 3 || range.location == 7) {
        textField.text = "\(textField.text!)-\(string)"
        return false
    }
    // 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 false
    }
    return true
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    // All digits entered
    if (range.location == 13) {
        return NO;
    }
    // Auto-add hyphen before appending 4rd or 7th digit
    if (range.length == 0 && (range.location == 3 || range.location == 8)) {
        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 == 9)) {
        range.location--;
        range.length = 2;
        textField.text = [textField.text stringByReplacingCharactersInRange:range withString:@""];
        return NO;
    }
    return YES;
}

 

 

글자수 제한

objective - c

if (_pwTF.text.length == 4) {
  if ([string cStringUsingEncoding:NSUTF8StringEncoding]) {
    int isBackSpace = strcmp([string cStringUsingEncoding:NSUTF8StringEncoding], "\b");
    if (isBackSpace == -8) {
      return YES;
    }
  } else {
    return NO;
  }
} else {
  return YES;
}

swift

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
  if let char = string.cString(using: String.Encoding.utf8) {
    let isBackSpace = strcmp(char, "\\b") // \b 인식인 되지 않음. (Swift 에서 \문자열 출력시 "\"앞에 붙여야함.)
    // 백스페이스 값 -92
    if (isBackSpace == -92) { // 기존의 차이점이 Objective C 에서는 -8 값이였음.
      print("Backspace was pressed (-92)")
    }
  }
  return true
  }
}

참고: https://xodhks0113.blogspot.com/2019/07/ios-uitextfield-backspace-objective-c.html

 

대소문자 구분하지 않고 문자열 비교

for (int idx = 0; idx < [배열 count]; idx++) {
  if ([[[배열 objectAtIndex:idx] objectForKey:@"name"] rangeOfString:텍스트필드.text options:NSCaseInsensitiveSearch].location != NSNotFound) {
    [저장배열 addObject:[배열 objectAtIndex:idx]];
  }
}

 

 

텍스트필드에 입력값 레이블에 대입

사용자가 텍스트필드에 입력을 완료하면 Label에 보여주기

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
  guard let currentText = textField.text else { return true }
  let finalText = (currentText as NSString).replacingCharacters(in: range, withe: string)
  myLabel.text = finalText
  
  return true
}

 

728x90

'iOS > iOS' 카테고리의 다른 글

UITableView  (0) 2022.12.19
UIDatePicker  (0) 2022.12.08
UIView에 shadow 넣기  (0) 2022.11.23
UIBezierPath  (0) 2022.11.08
UICollectionView  (0) 2022.11.04

댓글