I currently have the following code:
class NewPostController: UIViewController {
@IBOutlet weak var MessageField: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
MessageField.text = "What's on your mind?"
MessageField.textColor = UIColor.lightGrayColor()
}
func textViewDidBeginEditing(MessageField: UITextView) {
if MessageField.textColor == UIColor.lightGrayColor() {
MessageField.text = ""
MessageField.textColor = UIColor.blackColor()
}
}
However, whenever I edit MessageField
, the code within textViewDidBeginEditing
doesn't run. I suspect this is because of an invalid way of referencing MessageField
within the function, but I don't know what to do.
Looks like you're not setting your UITextView
's delegate
.
class ViewController: UIViewController, UITextViewDelegate {
@IBOutlet weak var myTextView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
myTextView.delegate = self
}
func textViewDidBeginEditing(textView: UITextView) {
myTextView.text = String()
}
UITextViewDelegate Protocol Reference
And to make @DanielStorm's answer work in Swift 3:
func textViewDidBeginEditing(_ textView: UITextView) {
myTextView.text = ""
}
In addition to the answers already given, I'd probably take the approach of storing whether it's been cleared initially as an instance variable on your class. In most use cases, the user would expect it to be cleared only when they begin editing the first time (to get rid of any placeholder text):
func textViewDidBeginEditing(_ textView: UITextView) {
if !self.textViewClearedOnInitialEdit {
self.textView.text = ""
self.textViewClearedOnInitialEdit = true
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With