LoginSignup
1

More than 3 years have passed since last update.

Swift UITextViewのplaceholder

Posted at

UITextViewにplaceholderがない!?

twitter風アプリを作ろうと思った時にtextfieldと同じようにtextView.placeholder = ""って感じでコードを書くと
Value of type 'UITextView' has no member 'placeholder'と怒られてしまいました。
え、textViewってplaceholderないの...
ということで、なんとかしてtextViewplaceholderを実装していきましょう。

今回はUITextViewを継承したTextViewというclassを作成してそのTextViewの中にUILabeladdSubViewしていきます。

TextView.swift
class TextView: UITextView {

    public let placeholderLabel: UILabel = {
        let label = UILabel()
        label.textColor = .lightGray
        label.font = .systemFont(ofSize: 18)
        label.numberOfLines = 0
        return label
    }()

    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        addSubview(placeholderLabel)

        placeholderLabel.translatesAutoresizingMaskIntoConstraints = false
        let cons = [
            placeholderLabel.topAnchor.constraint(equalTo: topAnchor, constant: 8),
            placeholderLabel.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 5),
            placeholderLabel.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -5),
        ]

        NSLayoutConstraint.activate(cons)
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

こんな感じでTextViewを定義しました。

あとはViewControllertextViewを表示するだけですね!

ViewController.swift
class ViewController: UIViewController {

    let textView: TextView = {
        let textView = TextView()
        textView.placeholderLabel.text = "placeholderだよー"
        textView.font = .systemFont(ofSize: 18)
        return textView
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        view.addSubview(textView)
        textView.frame = .init(x: 0, y: 100, width: view.frame.size.width, height: view.frame.size.height-200)
    }
}

これでいい感じに表示されました!
でも、このままだと入力した文字とplaceholderLabelの文字が重なってしまいますね。
んー、どうしよっかと考えた結果UITextViewDelegatetextViewDidChange(_ textView: UITextView)を使うことにしました。

ViewController.swift
extension ViewController: UITextViewDelegate {
    func textViewDidChange(_ textView: UITextView) {
        if textView.text.isEmpty {
            self.textView.placeholderLabel.alpha = 1
        } else {
            self.textView.placeholderLabel.alpha = 0
        }
    }
}

こんな感じです。
textView.textが空だったらplaceholderLabelを表示し、そうでなかったらplaceholderLabelを非表示にする。

まとめ

textViewにplacehoderを実装するだけで結構コード書かないといけないですね笑
もっと簡単に実装できる方法があればどなたか教えてください!

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1