Danny의 iOS 컨닝페이퍼
article thumbnail
Published 2022. 12. 20. 20:36
[iOS/Swift] UITextField 설정 UIKit/Swift
반응형

1. 텍스트 필드 여러 설정들

  1. UI 관련
<swift>
textField.frame.size.height = 22 // 프레임 높이 textField.borderStyle = .roundedRect // 테두리 스타일 textField.autocorrectionType = .no // 자동 수정 활성화 여부 textField.spellCheckingType = .no // 맞춤법 검사 활성화 여부 textField.autocapitalizationType = .none // 자동 대문자 활성화 여부 textField.placeholder = "이메일 입력" // 플레이스 홀더 textField.clearButtonMode = .always // 입력내용 한번에 지우는 x버튼(오른쪽) textField.clearsOnBeginEditing = false // 편집 시 기존 텍스트필드값 제거?

 

  1. 키보드 관련
<swift>
textField.returnKeyType = .done // 키보드 엔터키(return, done... ) textField.keyboardType = UIKeyboardType.emailAddress // 키보드 타입 textField.becomeFirstResponder() // 화면에서 첫번째로 반응(포커스 시킴) textField.resignFirstResponder() // 첫번째 반응을 중지

 

2. TextField 델리게이트 패턴

  • 사용법
<swift>
// 델리게이트 패턴: 객체와 객체간의 커뮤니케이션 (의사소통을 한다) // 즉. 뷰컨트롤러 대신에 일을 수행하고 그 결과값을 전달할 수 있습니다. 1) UITextFieldDelegate //프로토콜 채택, 바로 사용하는 대신 확장으로 많이 사용합니다. extension ViewController: UITextFieldDelegate { } // 텍스트필드의 프로토콜을 사용하기 위해선 사용할 객체를 연결 시켜줘야 한다.(위임) 2) textField.delegate = self // 텍스트필드.대리자 = ViewController의 객체를 담는다 3) UITextFiel의 메서드들 사용하여 코드 작성합니다.

 

  • textField 메서드
<swift>
// 입력이 끝날때 호출 (끝낼지 말지를 허락) func textFieldShouldEndEditing(_ textField: UITextField) -> Bool { return true } // 입력이 실제 끝날때 호출 (시점) func textFieldDidEndEditing(_ textField: UITextField) { textField.text = "입력을 마쳤습니다." } // 입력을 시작할때 호출 (시작할지 말지를 물어보는 것) func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool { return true } // 입력이 시작되면 호출 (시점) func textFieldDidBeginEditing(_ textField: UITextField) { } // 내용을 삭제할 때 호출 (삭제할지 말지를 물어보는 것) .clearButtonMode과 연관 func textFieldShouldClear(_ textField: UITextField) -> Bool { return true } // 한글자 한글자 입력/지워질때마다 호출 ---> true(입력 허락), false(입력 거부) func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { print("텍스트필드의 입력값: \(string)") return true } // 엔터키가 눌러졌을때 호출 (동작할지 말지 물어보는 것) func textFieldShouldReturn(_ textField: UITextField) -> Bool { return true } // 입력이 끝날때 호출 (끝낼지 말지를 물어보는 것) func textFieldShouldEndEditing(_ textField: UITextField) -> Bool { print("입력을 마쳤습니다") return true }

 

 

3. Cheat Sheet

3.1. 리턴 버튼 누를 때 다음 텍스트 필드로 이동

(becomeFirstResponder, resignFirstResponder 키워드)

// 로직을 추가하여 여려 텍스트필드도 가능합니다.
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if textField == self.emailTextField {
self.passwordTextField.becomeFirstResponder()
} else if textField == self.passwordTextField {
self.passwordTextField.resignFirstResponder()
}
return true
}
// 만약 빈문자열이면 리턴키 동작안하게 만들게 한다.
// 다음 텍스트로 넘어가 빈문자열이 아니면 키보드 내려가게 하기
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
// 두개의 텍스트필드를 모두 종료 (키보드 내려가기)
if emailTextField.text != "", passwordTextField.text != "" {
passwordTextField.resignFirstResponder()
return true
// 두번째 텍스트필드로 넘어가도록
} else if emailTextField.text != "" {
passwordTextField.becomeFirstResponder()
return true
}
return false
}

3.2. 텍스트 필드에서 글자 수 제한 및 숫자만 사용 (feat. 백스페이스)

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")
if (isBackSpace == -92) {
return true
}
}
// 숫자만 && 글자수 제한
guard Int(string) != nil || string == "" else { return false }
guard textField.text!.count < 3 else { return false }
return true
}
// 여러개의 텍스트 필드중에 사용하고 싶은거 고를 때 (연산자를 통하여 확인)
if textField == emailTextField {
}

3.3. 플레이스 홀더 동적으로 움직이게 만들기 (Label 사용)

  1. NSLayoutConstraint 사용 시
  • view 세팅
    1. 플레이스 홀더로 사용할 Label을 만들어 줍니다.
    2. 레이아웃을 잡을 때 따로 변수 centerYAnchor를 생성해 준다 (고정시키면 안 됨)
  • 텍스트 필드 델리게이트 메서드 세팅
    1. textFieldDidBeginEditing (입력 시점)에서 centerYAnchor를 변경 및 폰트 사이즈 변경을 합니다
    2. textFieldDidEndEditing (입력이 끝난 시점) 다시 처음 값으로 변경을 합니다.
    // 1. Y축을 따라 움직일 수 있도록 변수를 만들어준다.
    // 레이아웃 제약조건에 만들어 놓은 변수를 넣어준다.
    var placeHolderLabelCenterYAnchor = placeHolderLabel.CenterYAnchor.constraint(equalTo: emailTextField.centerYAnchor)
    NSLayoutConstraint.activate([
    placeHolderLabel.leadingAnchor.constraint(equalTo: emailTextField.leadingAnchor, constant: 8),
    placeHolderLabel.trailingAnchor.constraint(equalTo: emailTextField.trailingAnchor, constant: 8),
    placeHolderLabelCenterYAnchor
    ])
    // 2. 만들어 놓은 변수를 사용하여 제약조건을 변경
    func textFieldDidBeginEditing(_ textField: UITextField) {
    if textField == emailTextField {
    placeHolderLabel.font = UIFont.systemFont(ofSize: 11)
    // 오토레이아웃 업데이트
    placeHolderLabelCenterYAnchor.constant = -13
    }
    UIView.animate(withDuration: 0.3) {
    self.emailTextField.superview?.layoutIfNeeded() // Textfield의 슈퍼뷰를 업데이트
    // self.view.layoutIfNeeded() // viewcontroller의 뷰를 업데이트 (상황에 맞게 사용)
    }
    }
    func textFieldDidEndEditing(_ textField: UITextField) {
    // 선택한 textField가 emailTextField이고, 공백일 때 제약 조건 변경
    if textField == emailTextField, emailTextField.text == "" {
    placeHolderLabel.font = UIFont.systemFont(ofSize: 18)
    placeHolderLabelCenterYAnchor.constant = 0
    }
    }

 

  1. SnapKit 사용 시 (편리하네요.)
    textfield 내부에 뷰가 한 개 더 있어서 SuperView를 업데이트시켜주면 됩니다.
    func textFieldDidBeginEditing(_ textField: UITextField) {
    self.placeHolder.snp.updateConstraints {
    $0.centerY.equalTo(textField).offset(-10)
    }
    UIView.animate(withDuration: 1) {
    self.placeHolder.font = .systemFont(ofSize: 10)
    self.placeHolder.superview?.layoutIfNeeded() // Textfield의 슈퍼뷰를 업데이트
    // self.view.layoutIfNeeded() // viewcontroller의 뷰를 업데이트 (상황에 맞게 사용)
    }
    }
    func textFieldDidEndEditing(_ textField: UITextField) {
    placeHolder.snp.updateConstraints {
    $0.center.equalTo(textField)
    }
    UIView.animate(withDuration: 0.5) {
    self.placeHolder.font = .systemFont(ofSize: 16)
    self.placeHolder.superview?.layoutIfNeeded()
    // self.view.layoutIfNeeded()
    }
    }
    updateConstraints만 해주면 됩니다.

3.4. 텍스트 필드 입력 못하도록 수정(잠금)

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if textField == idTextField {
return false
}
return true
}

3.5. Padding 만들기 (공간 만들기)

위의 그림과 같이 좌측에 공백을 주는 방법입니다.

UITextField의 익스텐션

extension UITextField {
func addLeftPadding() {
let paddingView = UIView(frame: CGRect(x: 0, y: 0, width: 10, height: self.frame.height))
self.leftView = paddingView
self.leftViewMode = ViewMode.always
}
}
// 사용
textFiled.addLeftPadding()

 

4. 참고하면 더 좋은 블로그

 

Swift : 기초문법 [UITextField]

UITextField TextField는 기본적으로 다크 모드와 라이트 모드를 자동으로 구별한다. Text Input Traits Text 입력 type를 설정 Content Type semantic meaning을 나타냄. 이 프로퍼티를 사용하면, 사용자가 입력하는

seons-dev.tistory.com

 

[Swift] UITextField Left padding 넣어주기 !!

안녕하세요 :] 오늘 정리할 내용은 UITextField의 Text에 left padding 값을 주는 거예요. 보통 UITextField의 값을 입력할 때면 너무 왼쪽에 딱 붙어서 경계선과 글자의 구분이 애매하죠. 그래서 왼쪽에 약

developer-fury.tistory.com

 

 

 

반응형
profile

Danny의 iOS 컨닝페이퍼

@Danny's iOS

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!