'UItextView delegate swift - textViewDidBeginEditing not called

I've seen the other topics dealing with UITextView delegate, but can't seem to find where my issue come from. Here is my code, but when I modify my UITextView, nothing happens and textViewDidBeginEditing is not called.

import UIKit
var textView1 = UITextView()

class ViewController: UIViewController, UITextViewDelegate {
    override func viewDidLoad() {
        super.viewDidLoad()

        textView1.delegate = self
        textView1 = UITextView(frame: CGRect(x:24,y: 100,width: 340,height: 290))
        textView1.textColor = UIColor.black
        textView1.backgroundColor = UIColor(red: 0.00, green: 0.00, blue: 0.00, alpha: 0.00)
        textView1.text = "textView 1"
        view.addSubview(textView1)
    }

    func textViewDidBeginEditing(_ textView: UITextView) {
        print("print1")
    }

    func textViewDidEndEditing(_ textView: UITextView) { 
        print("print2")
    }
}

I've tried with UITextField, but nothing changed, delegate functions still not called.



Solution 1:[1]

You are setting a value from a nil object, you have to Initialize it and then you can set the target delegate.

Solution 2:[2]

Just move your textView1.delegate = self 2 lines down. You are setting delegate for UITextField but in next line you are creating new object without any delegate ;)

Solution 3:[3]

enter image description here

please change the position of textView1.delegate = self with next line.

Solution 4:[4]

Please try with this code

import UIKit

class ViewController: UIViewController, UITextViewDelegate {

    var textView1 = UITextView()
    override func viewDidLoad() {
        super.viewDidLoad()
        textView1 = UITextView(frame: CGRect(x:24,y: 100,width: 340,height: 290))
        textView1.delegate = self
        
        textView1.textColor = UIColor.black
        textView1.backgroundColor = UIColor(red: 0.00, green: 0.00, blue: 0.00, alpha: 0.00)
        textView1.text = "textView 1"
        view.addSubview(textView1)
    }

    func textViewDidBeginEditing(_ textView: UITextView) {
        print("print1")
    }

    func textViewDidEndEditing(_ textView: UITextView) { 
        print("print2")
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Gabs
Solution 2 Micha? Kwiecie?
Solution 3 Bijender Singh Shekhawat
Solution 4 Daya Kevin