Mrwolfy Mrwolfy - 1 year ago 170
iOS Question

UITextView delegate methods

I am trying to get delegate methods to work with UITextView, but it's not working for some reason.

I have declared in my viewController.h that it is a UITextViewDelegate

I am trying to get the following code to work to erase the default code "TEXT" when I tap on the textView.

- (void)textViewDidBeginEditing:(UITextView *)textView {

if (myTextView.text == @"TEXT") {
[myTextView setText:@""];

NSLog(@"did begin editing");

I expected to the text to be cleared and to see the NSLog print when I tap on the textView and the keyboard appears. Nothing at all happens

Using a text view by the way because I need to scale the view based on its content size and seems that the textView has a contentSize property, whit label and textField do not.


I should have used:

if ([myTextView.text isEqualToString:@"TEXT"]) {
[myTextView setText:@""]; }

here is the project if you want to take a look.

Answer Source

this method is missing from your Test2ViewController.m file:

- (void)viewDidLoad {
    [myTextView setDelegate:self];

or you can connect the delegate in the Interface Builder as well, if you prefer that way better.


add this method to you class for controlling the return key.

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    if ([text isEqualToString:@"\n"]) {
        NSLog(@"Return pressed, do whatever you like here");
        return NO; // or true, whetever you's like

    return YES;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download