views:

742

answers:

2

Hello,

I have a small iPhone Project with a UITextView on my View, designed in the Interface Builder. In my Viewcontroller is an IBAction Method and I connected the UITextView to that IBAction. I also added in my controller .h the <UITextViewDelegate>.

In my .m File I added the Method:

- (void)textViewDidChange:(UITextView *)textView{
     int count = [textView.text length];
     charCount.text = (NSString *)count;
}

But when the App is running and I type something into the textView, the Method textViewDidChange will never be reached. Why is that? I also tried to add textView.delegate = self in the ViewDidLoad Method, but then the App crashes without any Message in the Debugger.

Has anyone a Tip what I´m doing wrong?

Thank you so much

twickl

+1  A: 

You're on the right track - the reason the method isn't getting called is that you're not setting the text view's delegate before you change its text. I notice in your question you say you tried to set testView.delegate = self; - did you mean textView? Often typos like that will crash the program without a debugger message.

Also, the textFieldDidChange: method isn't defined in the UITextFieldDelegate protocol. You may have meant textField:shouldChangeCharactersInRange:replacementString: - this is the delegate method that actually gets called whenever a text field changes its contents. Just connecting your own method to an IBAction doesn't guarantee what I think you want.

If neither of those are your problem, then you need to go back and double-check all your various connections, both in IB and in your class header file. Your header should look something like this:

// MyViewController.h

@interface MyViewController : UIViewController  {
    UITextField *textView;
}

@property(nonatomic,retain) IBOutlet UITextField *textView;

- (IBAction)myAction:(id)sender;

@end

And your implementation:

// MyViewController.m

@implementation MyViewController

@synthesize textView;

- (IBAction)myAction:(id)sender {
    // Do something
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
     int count = [textView.text length];
     charCount.text = (NSString *)count;
}

@end

The important document in this case is the UITextFieldDelegate protocol reference.

Tim
Oh, I meant textView.delgate = self, and that´s what I set in ViewDidLoad. But that will crash or better freeze the App in the Simulator.
twickl
Can you set a breakpoint right before that line and step through it? That way you can figure out more precisely what's gone wrong. (Did you hook up the `textView` outlet of the view controller to the view itself in IB?)
Tim
+1  A: 

Oh, I realised what´s wrong!

charCount musst be set in this way:

charCount.text = [[NSNumber numberWithInt:count] stringValue];

Now it works!

twickl
Can't believe I missed that. Well done :)
Tim