[iPhone SDK] [新手] UITextView textViewDidChange不会被调用?

3 iphone cocoa-touch objective-c

我的View上有一个带有UITextView的小型iPhone项目,在Interface Builder中设计.在我的Viewcontroller中有一个IBAction方法,我将UITextView连接到IBAction.我还在我的控制器中添加了.h <UITextViewDelegate>.

在我的.m文件中,我添加了方法:

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

但是当App运行并且我在textView中键入内容时,将永远不会到达方法textViewDidChange.这是为什么?我还尝试在ViewDidLoad方法中添加textView.delegate = self,但随后App在调试器中没有任何消息时崩溃.

有没有人提示我做错了什么?

非常感谢

twickl

Tim*_*Tim 8

您处于正确的轨道 - 未调用该方法的原因是您在更改文本之前未设置文本视图的委托.我在你的问题中注意到你说你试图设置testView.delegate = self;- 你的意思是textView?像这样的拼写错误会在没有调试器消息的情况下使程序崩溃.

此外,该textFieldDidChange:方法未在UITextFieldDelegate协议中定义.您可能意味着textField:shouldChangeCharactersInRange:replacementString:- 这是在文本字段更改其内容时实际调用的委托方法.只是将自己的方法连接到IBAction并不能保证我认为你想要的东西.

如果这些都不是您的问题,那么您需要返回并仔细检查IB和您的类头文件中的所有各种连接.您的标题应如下所示:

// MyViewController.h

@interface MyViewController : UIViewController  {
    UITextField *textView;
}

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

- (IBAction)myAction:(id)sender;

@end
Run Code Online (Sandbox Code Playgroud)

你的实施:

// 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
Run Code Online (Sandbox Code Playgroud)

在这种情况下,重要的文档是UITextFieldDelegate协议引用.