Swift3 – UITextViewにPlaceholderをLabelを使わずに実装する方法
環境
- Swift3
- Xcode8
- Mac Os Sierra
Step1
UITextViewDelegate
をデリゲート
class MyViewController: UIViewController, UITextViewDelegate {
step2
viewWillAppear
に下記のように書く
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
bodyTextView.text = "Placeholder"
bodyTextView.textColor = UIColor.lightGray
}
step3
textViewDidBeginEditing
とtextViewDidEndEditing
を実装
func textViewDidBeginEditing(_ textView: UITextView) {
if bodyTextView.textColor == UIColor.lightGray {
bodyTextView.text = nil
bodyTextView.textColor = UIColor.black
}
}
func textViewDidEndEditing(_ textView: UITextView) {
if bodyTextView.text.isEmpty {
bodyTextView.text = "Placeholder"
bodyTextView.textColor = UIColor.lightGray
}
}