UITextViewにplaceholderがない!?
twitter風アプリを作ろうと思った時にtextfieldと同じようにtextView.placeholder = ""って感じでコードを書くと
Value of type 'UITextView' has no member 'placeholder'と怒られてしまいました。
え、textViewってplaceholderないの...
ということで、なんとかしてtextViewにplaceholderを実装していきましょう。
今回はUITextViewを継承したTextViewというclassを作成してそのTextViewの中にUILabelをaddSubViewしていきます。
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を定義しました。
あとはViewControllerでtextViewを表示するだけですね!
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の文字が重なってしまいますね。
んー、どうしよっかと考えた結果UITextViewDelegateのtextViewDidChange(_ textView: UITextView)を使うことにしました。
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を実装するだけで結構コード書かないといけないですね笑
もっと簡単に実装できる方法があればどなたか教えてください!