Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 789
dbalagula23 Avatar asked Jun 03 '15 01:06

dbalagula23


3 Answers

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

like image 130
Daniel Storm Avatar answered Nov 12 '22 10:11

Daniel Storm


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

func textViewDidBeginEditing(_ textView: UITextView) {
    myTextView.text = ""
}
like image 35
brunocortes06 Avatar answered Nov 12 '22 10:11

brunocortes06


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
    }
}
like image 43
John Rogers Avatar answered Nov 12 '22 12:11

John Rogers