UITextView delegate methods

Viewed 28462

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.

UPDATE:

I should have used:

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

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

6 Answers

Swift 4,5

write this extension at the bottom of your controller. it can be use to show and hide placeholder in textView.

extension ViewController: UITextViewDelegate {
    func textViewDidBeginEditing(_ textView: UITextView) {
        if textView == yourTxtView {
            txtNote.text = ""
            txtNote.textColor = .black
        }
    }

    func textViewDidEndEditing(_ textView: UITextView) {
        if textView == yourTxtView {
            txtNote.text = "Note:"
            txtNote.textColor = .gray
        }
    }
}
Related