현재 개발 중인 앱에 UITextField 와 UITextView 를 한 화면에서 사용하고 있다. 둘 모두에 Placeholder를 적용했는데, UITextField 는 Attribute Inspector에서 Placeholder 옵션이 있기 때문에 쉽게 설정했고, UITextView 는 이 방법을 통해 코드로 구현했다.
테스트를 하다보니 이슈를 하나 발견했는데,
UITextField는 실제 입력이 이루어져야 Placeholder가 사라진다.UITextView는 입력창에 커서가 위치하면 Placeholder가 사라진다.
사소한 차이지만, 이 차이가 불편했기에 UITextField 의 Placeholder를 코드로 구현하여 동작 방식을 UITextView 와 통일하고자 한다.
해결 방안
우선
UITextField의 Attribute Inspector에서 Placeholder 설정을 제거한다.textFieldDidBeginEditing와textFieldDidEndEditing를 추가한다.func textFieldDidBeginEditing(_ textField: UITextField) { if textField.text == "Placeholder" { textField.text = "" textField.textColor = .black } } func textFieldDidEndEditing(_ textField: UITextField) { if textField.text?.isEmpty ?? true { textField.text = "Placeholder" textField.textColor = .lightGray } }