2

So I have a UITextView and some placeholder text inside. When the user taps inside the the view, I want to execute some code, i.e. clear the placeholder text. I was trying to create an IBAction but it won't let me. I looked it up online and found this UITextViewDelegate Protocol Reference but I can't figure out how to use it. A lot of the examples I've found for working with delegates are Objective-C and I am working in Swift.

Sorry for the simple question I'm new at this.

Thanks!

Jake
  • 319
  • 1
  • 7
  • 21

2 Answers2

3

Given an IBOutlet to a text view someTextView, all you need to do is make your class conform to UITextViewDelegate, set that text view's delegate to self, and implement the textViewDidBeginEditing method:

class ViewController: UIViewController, UITextViewDelegate {

    @IBOutlet weak var someTextView: UITextView!

    override func viewDidLoad() {
        super.viewDidLoad()

        someTextView.delegate = self
    }

    func textViewDidBeginEditing(textView: UITextView) {
        println("Some code")
    }
}
Ian
  • 12,538
  • 5
  • 43
  • 62
1

The View Controller should adhere to UITextViewDelegate. Then make sure to implement textViewDidBeginEditing delegate methods. The below code should clear the default place holder text when the user starts editing the textview.

import UIKit

class ViewController: UIViewController, UITextViewDelegate {

    @IBOutlet weak var textView: UITextView!


    override func viewDidLoad() {
        super.viewDidLoad()
        self.textView.delegate = self
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

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

}
rshankar
  • 3,045
  • 2
  • 18
  • 19