Help us understand the problem. What is going on with this article?

【Swift】UITextViewに複数行対応のplaceholderを付ける

More than 1 year has passed since last update.

UITextViewにplaceholderが無い!?

Swift界隈では常識?なのかもしれませんが、Swift歴が非常に浅い私には衝撃的でした。
ググると大昔からみんな困っているようで、やたら冗長なサンプルコードも多々。。。

placeholderの複数行対応はそこまで需要ないかもですが、今回たまたま欲しかったので作成。

UITextViewに複数行対応placeholderを付ける

単純にTextView内にplaceholder用TextViewを入れて、RXで入力検知してplaceholderと同じ挙動させてるだけ。

コード

import UIKit
import RxSwift
import SnapKit

/// 複数行対応Placeholder付きUITextView
final class UITextViewWithPlaceholder: UITextView {
    private let placeholderTextView = UITextView()
    private let disposeBag = DisposeBag()

    init(placeholder: String = "", font: UIFont = UIFont.systemFont(ofSize: UIFont.systemFontSize)) {
        super.init(frame: CGRect.zero, textContainer: nil)

        // Placeholder
        self.placeholderTextView.font = font
        self.placeholderTextView.backgroundColor = UIColor.clear
        self.placeholderTextView.isUserInteractionEnabled = false
        self.placeholderTextView.textColor = UIColor(hex: ColorConstant.TEXT_PLACEHOLDER)
        self.addSubview(self.placeholderTextView)

        // AutoLayout
        self.placeholderTextView.snp.makeConstraints{ make in
            make.center.equalToSuperview()
            make.width.equalToSuperview()
            make.height.equalToSuperview()
        }

        // RX
        self.rx.text.orEmpty
            .subscribe(onNext: {[weak self] value in
                self?.placeholderTextView.text = value.isEmpty ? placeholder : nil
            }).disposed(by: disposeBag)
    }

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

利用方法

使う側は普通のTextViewと同じように使用可能。

let textView = UITextViewWithPlaceholder(placeholder: "どうして\nplaceholderないの…")

結果

Swift.gif

所感

extensionでUITextView拡張して、UITextViewDelegateをごにょごにょする方式でも良いと思いますが、とにかくこれくらい標準で提供して欲しい…

同じ思いをした事ある方もいるのではないでしょうか…:disappointed_relieved:

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした