UITextField
- 사용자가 단일 줄의 텍스트를 입력할 수 있게 해주는 UI 컴포넌트
- 로그인 화면, 검색창, 회원가입 등에서 자주 사용
주요 속성
| 속성 | 설명 |
|---|
text | 사용자가 입력한 문자열 |
placeholder | 입력 전 회색 안내 텍스트 |
textColor | 텍스트 색상 |
font | 텍스트 폰트 |
isSecureTextEntry | true이면 비밀번호 입력처럼 •••• 표시 |
keyboardType | 이메일 키보드, 숫자 키보드 등 지정 가능 |
returnKeyType | 리턴 키 모양 설정 (예: done, go, search) |
autocapitalizationType | 자동 대문자 설정 (예: 이메일이면 .none) |
autocorrectionType | 자동 수정 설정 |
clearButtonMode | 텍스트 오른쪽 x 버튼 표시 여부 |
borderStyle | .none, .line, .bezel, .roundedRect 등 |
주요 메서드
| 메서드 | 설명 |
|---|
becomeFirstResponder() | 포커스를 줘서 키보드 표 |
resignFirstResponder() | 포커스를 해제하고 키보드 내림 |
addTarget(_:action:for:) | 텍스트가 바뀔 때 이벤트 감지 (예: .editingChanged) |
UITextFieldDelegate
- 텍스트 필드의 행동을 제어하고 싶을 때 사용
textField.delegate = self로 설정해주어야 작동
extension ViewController: UITextFieldDelegate {
func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
return true
}
func textFieldDidEndEditing(_ textField: UITextField) {
}
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
return true
}
func textFieldDidBeginEditing(_ textField: UITextField) {
}
func textFieldShouldClear(_ textField: UITextField) -> Bool {
return true
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
return true
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
return true
}
func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
return true
}
}
💡 패딩 추가하는 방법
UITextField는 좌우 패딩이 없음
- 다음처럼
leftView와 rightView를 활용해 패딩 추가
textField.leftView = UIView(frame: CGRect(x: 0, y: 0, width: 10, height: 0))
textField.leftViewMode = .always