Reputation:
I have a small iPhone Project with a UITextView on my View, designed in the Interface Builder. There's a IBAction Method in my Viewcontroller 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
Upvotes: 3
Views: 8300
Reputation:
Oh, I realised what´s wrong!
charCount musst be set in this way:
charCount.text = [[NSNumber numberWithInt:count] stringValue];
Now it works!
Upvotes: 1
Reputation: 60110
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.
Upvotes: 8