Search code examples
iphoneobjective-ccocoa-touchdelegatesuitextview

UITextViewDelegate: how to set the delegate in code (not in IB...)


Suppose you have an UITextView and you would like to set the delegate of this UITextView.

First thing is that you put this in your header file:

@interface myViewController : UIViewController <UITextViewDelegate> { ...

Then, if you were using IB, you would click the UITextView, and connect the delegate outlet with File's Owner. This would allow you to use commands such as - (BOOL)textViewShouldBeginEditing:(UITextView *)aTextView { etc.

Now, suppose you wanted to do this programatically. I found this suggestion on here:

textView.delegate = yourDelegateObject;

But I have no idea what 'yourDelegateObject' stands for. In IB, I am connecting with File's Owner... so in code, it would need to be textView.delegate = File's Owner. But what is the File's Owner in this case? myViewController? UIViewController?

I don't really understand the principle, I suppose. Any help would be very much appreciated.


Solution

  • As others have stated, set the delegate property of the UITextView. The most common delegate object is self.

    To elaborate on "delegate object": the delegate object is the class (implementing the UITextViewDelegate protocol) that you want the events to respond to. For example, if you use a class instance instead of self, the UITextView will send its events to the implementations of the delegate methods in that class.