投稿の経緯
前回投稿した↓記事の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
}
}
これだけで実装できます
確認動画
おわりに
今回はUITextViewにプレースホルダーをつける実装方法を紹介しました。
この記事が誰かの役に立てば幸いです。
最後までご覧いただきありがとうございました!