FamousMaxy
FamousMaxy

Reputation: 686

UITextViewDelegate inside a class func

I am using swift 3 and I have a class as the following:

class Assistor : NSObject , UITextViewDelegate {


private override init() {

}

class func RegisterTextView(uiview:UIView) {

    if let RegisteredView = uiview as? UITextView {
        RegisteredView.delegate = self as! UITextViewDelegate
    }
}


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

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

From a normal uiviewcontroller I want to call the Assistor function like this in the viewDidLoad:

class InqueryDetailsViewController: UIViewController {
    @IBOutlet weak var AnswerTextView:UITextView!
override func viewDidLoad() {
    super.viewDidLoad()

Assistor.RegisterTextView(uiview: AnswerTextView)
}
}

As it is clearly, I want to trigger textViewDidBeginEditing from the assistor not from the uiviewcontroller. how to do that?

Upvotes: 1

Views: 74

Answers (1)

Reinier Melian
Reinier Melian

Reputation: 20804

First your Assistor must be declared as object, if you want only one you can make it as singleton, you need to change the init to public, and change the registerTextView as instance method

try with this

class Assistor : NSObject , UITextViewDelegate {

    //Singleton
     static let sharedInstance: Assistor = Assistor()

    override init() {
        super.init()
    }

    func registerTextView(uiview:UIView) {
        if let RegisteredView = uiview as? UITextView {
            RegisteredView.delegate = self as! UITextViewDelegate
        }
    }


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

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

Using it

class ViewController: UIViewController {

    @IBOutlet weak var textView: UITextView!

    var assistor : Assistor = Assistor()

    override func viewDidLoad() {
        super.viewDidLoad()

        self.assistor.registerTextView(uiview: self.textView)
        //using as singleton
        //Assistor.sharedInstance.registerTextView(uiview: self.textView)
    }
}

Hope this helps

Upvotes: 1

Related Questions