8

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.

Daniel Storm
  • 18,301
  • 9
  • 84
  • 152
dbalagula23
  • 307
  • 1
  • 5
  • 13
  • http://stackoverflow.com/questions/27652227/text-view-placeholder-swift – Adrian Jun 03 '15 at 01:37
  • 2
    I don't know swift, but I suppose you must delegate your text view to execute textViewDidVeginEditing. You must call [MessageField setDelegate:self] (equivalent in swift syntax) and you must add – Beto Jun 03 '15 at 01:38
  • @AdrianB, the specifics of the code don't change the fact that I can write in `println("Hi")` within `textViewDidBeginEditing`, but it still doesn't run. – dbalagula23 Jun 03 '15 at 01:41

3 Answers3

23

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

Daniel Storm
  • 18,301
  • 9
  • 84
  • 152
1

And to make @DanielStorm's answer work in Swift 3:

func textViewDidBeginEditing(_ textView: UITextView) {
    myTextView.text = ""
}
clearlight
  • 12,255
  • 11
  • 57
  • 75
1

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
    }
}
John Rogers
  • 2,192
  • 19
  • 29