0
1

More than 1 year has passed since last update.

[Swift/UIKit]UITextViewにプレースホルダーをつける(超簡単!)

Posted at

投稿の経緯

前回投稿した↓記事のTextViewにプレースホルダーを追加実装したので記事にします。

プレースホルダーの実装方法を調査すると、少し複雑な方法で実装されている記事が多いと感じました。
今回紹介する方法はUILabelを使った簡単な方法なので参考にしていただければと思います。

実装

プレースホルダー(UILabel)をtextViewに配置する

ViewController.swift
private func setUpPlaceHolder() {
    let frame = CGRect(
        x: 5,
        y: 0,
        width: 20,
        height: TEXT_VIEW_HEIGHT
    )
    placeHolder.frame = frame
    placeHolder.text = "Aa"
    placeHolder.textColor = .gray
    placeHolder.font = UIFont.systemFont(ofSize: 16)
    textView.addSubview(placeHolder)
}

textViewDidChangeが呼ばれたタイミングでプレースホルダーの表示/非表示を制御する

ViewController.swift
func textViewDidChange(_ textView: UITextView) {
    if textView.text == "" {
        placeHolder.isHidden = false
   } else {
        placeHolder.isHidden = true
    }
}

これだけで実装できます

確認動画

Simulator_Screen_Recording_-iPhone_14-_2023-08-11_at_12_20_24_AdobeExpress.gif

おわりに

今回はUITextViewにプレースホルダーをつける実装方法を紹介しました。
この記事が誰かの役に立てば幸いです。

最後までご覧いただきありがとうございました!

0
1
0

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
0
1