Search code examples
iosswiftxcode6uitextviewuitextviewdelegate

How do you run a section of code when the user taps the UITextView in Swift?


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!


Solution

  • 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")
        }
    }