본문 바로가기
PROGRAMMING CODE/SWIFT

[UIKit] TextView placeholder 구현

by daye_ 2023. 12. 12.

 

TextView는 placeholder가 따로 있지 않아서 구현해줘야함!

 

 

 

 lazy var scriptTextView: UITextView = {
        let tv = UITextView()
        tv.text = "텍스트 입력"
        tv.text = textViewPlaceHolder
        tv.frame.size.height = 18
        tv.autocapitalizationType = .none
        tv.autocorrectionType = .no
        tv.spellCheckingType = .no
        tv.delegate = self
        tv.translatesAutoresizingMaskIntoConstraints = false
        return tv
    }()

...



extension MemoDetailView: UITextViewDelegate {
    func textViewDidBeginEditing(_ textView: UITextView) {
        if textView.text == textViewPlaceHolder {
            textView.text = nil
            textView.textColor = .black
        }
    }

    func textViewDidEndEditing(_ textView: UITextView) {
        if textView.text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
            textView.text = textViewPlaceHolder
            textView.textColor = .lightGray
        }
    }
}