开发者

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 &l开发者_如何学运维t;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.


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.


Most likely you want to assign a delegate to a current controller object, that is self:

textView.delegate = self;


yourDelegateObject = self.

you can use

textView.delegate = self;


The delegate is your UIViewController so it's

textView.delegate = self;


Try to put self as delegate:

textView.delegate = self;

So you need to put the function - (BOOL)textViewShouldBeginEditing:(UITextView *)aTextView in the implementation of your controller.


The delegate can be any object, it doesn't have to be the class the textField is created in, though usually it is - whenever this is true you will set it to self, though you can set it to any instanced object that conforms to the protocol (whenever a formal protocol is defined for the object).


Just assign it to self:

textView.delegate = self;


Swift:

textView.delegate = self


Make sure in your class you add UIItextFieldDelegate.

Example: say my class was called Pizza and my textField was called goodEats

class Pizza: UIViewController, UITextFieldDelegate {

//Then set the delegate in viewDidLoad 
override func viewDidLoad() {
super.viewDidLoad()

    goodEats.delegate = self

}
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜