LoginSignup
0
0

More than 1 year has passed since last update.

【Swift】UITextViewにプレースホルダーをつける

Posted at

まえがき

• notionでメモ程度に書いてるのをQiitaでまとめてみた!
• 自分用
• UITextViewにプレースホルダーねーじゃんってなったので作ってみた

プレースホルダー付きカスタムTextView↓

import UIKit

class CustomTextView: UITextView {

    var placeholderText: String? {
        didSet{ placeholderLabel.text = placeholderText }
    }

    let placeholderLabel: UILabel = {
        let label = UILabel()
        label.textColor = .gray
        label.translatesAutoresizingMaskIntoConstraints = false
        return label
    }()

    //y軸をセンターにするー
    var placeholderShouldCenter = true {
        didSet{
            if placeholderShouldCenter {
                NSLayoutConstraint.activate([
                    placeholderLabel.topAnchor.constraint(equalTo: self.topAnchor, constant: 6),
                    placeholderLabel.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 8),
                    placeholderLabel.centerYAnchor.constraint(equalTo: self.centerYAnchor, constant: 0)
                ])
            } else {

                NSLayoutConstraint.activate([
                    placeholderLabel.topAnchor.constraint(equalTo: self.topAnchor, constant: 6),
                    placeholderLabel.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 8)
                ])
            }
        }
    }

    override func awakeFromNib() {
        super.awakeFromNib()
        addSubview(placeholderLabel)
        //AutoLayoutの制約
        NSLayoutConstraint.activate([
            placeholderLabel.topAnchor.constraint(equalTo: self.topAnchor, constant: 6),
            placeholderLabel.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 8)
        ])
        //オブザーバーを使って監視
        NotificationCenter.default.addObserver(self, selector: #selector(handleTextDidChange), name: UITextView.textDidChangeNotification, object: nil)
    }
    //変更通知を受け取った時にplaceholderLabelをTextViewのtext.isEmptyで隠すか判断する
    @objc func handleTextDidChange() {

        placeholderLabel.isHidden = !text.isEmpty
    }


}


手順

storyboardのTextViewにちゃんとカスタムクラスを割りあってからコードと繋げよう

スクリーンショット 2021-10-29 20.56.00.png

ViewControllerはこんな感じ

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var textView: CustomTextView!

    @IBOutlet weak var centerYTextView: CustomTextView!

    override func viewDidLoad() {
        super.viewDidLoad()

        textView.placeholderText = "入力しろや"
        centerYTextView.placeholderShouldCenter = true
        centerYTextView.placeholderText = "YCenter"
    }


}


 完成イメージ

IMB_ksZshe.gif

終わりに

xibファイルはなくてもok
誰かの参考になれば幸いです
Qiitaさんいつもお世話になってるので感謝
間違えてるところ等ありましたら教えてくださいー

参考

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