I am a newbie and want to make a custom class for a UITextView where I will be able to get the text by tapping on it within the UITextView. How to create Custom UITextView class?
- 4You surely tried something. Don't hesitate to show your attempt, so that this does not look like a “write the code for me” question!ielyamani– ielyamani2019-05-14 06:23:53 +00:00Commented May 14, 2019 at 6:23
- Do you want to get the selected text within the whole text of the textview?RajeshKumar R– RajeshKumar R2019-05-14 07:28:11 +00:00Commented May 14, 2019 at 7:28
Add a comment |
3 Answers
Try this, I have created custom textview class and protocol that you need to confirm in your class and implement that method to get text of textview every time when you click textview.
class CustomTextView: UITextView { weak var delegateCustomTV: CustomTextViewDelegate? override func awakeFromNib() { super.awakeFromNib() let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.textViewTapped)) self.addGestureRecognizer(tapGestureRecognizer) } @objc func textViewTapped() { delegateCustomTV?.preparedText(text: self.text ?? "") } } protocol CustomTextViewDelegate: class { func preparedText(text: String) } use like i have used below,
class yourViewController: UIViewController, CustomTextViewDelegate { @IBOutlet weak var textView: CustomTextView! override func viewDidLoad() { super.viewDidLoad() textView.delegateCustomTV = self } func preparedText(text: String) { // You will get your text here when you click on textview print(text) } } Comments
Try this
override func viewDidLoad() { super.viewDidLoad() self.textView.delegate = self } extension YourViewController: UITextViewDelegate { //MARK:- TextView Editing begins Function func textViewDidBeginEditing(_ textView: UITextView) { //TextView Editing Begin Function } // MARK:- TextView text replaced Function func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool { //Character changed in textView return true } // MARK:- TextView End Editing function func textViewDidEndEditing(_ textView: UITextView) { //End editing of textView } } 3 Comments
vpoltave
self.textView.delegate = self you can't have this line of code in extension.vpoltave
And btw your answer not related to OP question: How to make that Custom TextView class?
steveSarsawa
I've added this code for any single class because question is for identifying
input text and i don't think that to identify text by using customClass is a good idea :(if you want to get text every time you tap textview you have to add tap gesture
override func viewDidLoad() { super.viewDidLoad() self.textView.delegate = self let tap = UITapGestureRecognizer(target: self, action: #selector(self.textViewTapped(_:))) self.textView.addGestureRecognizer(tap) } @objc func textViewTapped(_ sender: UITapGestureRecognizer){ print(textView.text) }