Swift3 – UITextViewにPlaceholderをLabelを使わずに実装する方法

環境

  • Swift3
  • Xcode8
  • Mac Os Sierra

Step1

UITextViewDelegateをデリゲート

class MyViewController: UIViewController, UITextViewDelegate {

step2

viewWillAppearに下記のように書く

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)


        bodyTextView.text = "Placeholder"
        bodyTextView.textColor = UIColor.lightGray


    }

step3

textViewDidBeginEditingtextViewDidEndEditingを実装

    func textViewDidBeginEditing(_ textView: UITextView) {
        if bodyTextView.textColor == UIColor.lightGray {
            bodyTextView.text = nil
            bodyTextView.textColor = UIColor.black
        }
    }


    func textViewDidEndEditing(_ textView: UITextView) {
        if bodyTextView.text.isEmpty {
            bodyTextView.text = "Placeholder"
            bodyTextView.textColor = UIColor.lightGray
        }
    }

藤沢瞭介(Ryosuke Hujisawa)
  • りょすけと申します。18歳からプログラミングをはじめ、今はフロントエンドでReactを書いたり、AIの勉強を頑張っています。off.tokyoでは、ハイテクやガジェット、それからプログラミングに関する情報まで、エンジニアに役立つ情報を日々発信しています!

未整理記事