Reputation: 329
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!
Upvotes: 2
Views: 1697
Reputation: 12758
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")
}
}
Upvotes: 3
Reputation: 3085
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 = ""
}
}
Upvotes: 1