dbalagula23
dbalagula23

Reputation: 307

How to clear UITextView upon editing?

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.

Upvotes: 8

Views: 13810

Answers (3)

Daniel Storm
Daniel Storm

Reputation: 18878

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

Upvotes: 23

John Rogers
John Rogers

Reputation: 2192

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
    }
}

Upvotes: 1

brunocortes06
brunocortes06

Reputation: 49

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

func textViewDidBeginEditing(_ textView: UITextView) {
    myTextView.text = ""
}

Upvotes: 1

Related Questions