UITextFieldDelegate问题

我有一个使用UITextFieldDelegate协议的iPad应用程序。 我宣布并实施完整的协议。 调用该协议的字段声明如下:

typingInput = [ [ [ UITextField alloc ] initWithFrame: textIn ] retain ]; dp.x = center.x; dp.y = center.y - 42; typingInput.center = dp; [ self addSubview: typingInput ]; [ typingInput release ]; typingInput.font = [ UIFont systemFontOfSize: 52.0 ]; [ typingInput setTextColor: [ UIColor whiteColor ] ]; typingInput.backgroundColor = [ UIColor colorWithWhite: 0.0 alpha: 0.0 ]; typingInput.alpha = 0.0; typingInput.userInteractionEnabled = NO; [ typingInput addTarget: self action: @selector(textField:shouldChangeCharactersInRange:replacementString:) forControlEvents: UIControlEventEditingChanged | UIControlEventAllEditingEvents ]; typingInput.text = @""; typingInput.autocorrectionType = UITextAutocorrectionTypeNo; typingInput.enablesReturnKeyAutomatically = YES; typingInput.delegate = self; 

问题在于

 - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange: (NSRange)qrange replacementString: (NSString *)str; 

在模拟器上,'str'的运行时types是nil或者NSCFString,根据这个:

 NSLog(@"class = %@, value='%@'", [ str class ], str ); 

一切正常,当我编辑string。

在iPad上,相同的日志logging返回:

 class = UIFieldEditor, value='<UIFieldEditor: 0xb5f400; frame = (0 0; 640 640); text = 'Foobar'; opaque = NO; layer = <UIWebLayer: 0x113ba0>>' 

当我尝试添加,更改或删除文本时,后续使用'str'作为NSString会导致iPad崩溃。 qrange也是无效的(长度是一些巨大的数字)。

UIFieldEditor是我没有使用的UIWebView.h的一部分。

在一定程度上改变协议成员的声明会影响行为。

由于我找不到这个问题的其他人,我不得不假定我做错了什么。

有任何想法吗?

shouldChangeCharactersInRange委托方法将自动由UITextField调用(通过设置其delegate属性)。 如果你已经实现了UITextField,也可以调用其他委托方法。

您不(也不应该)使用addTarget将委托方法显式连接到UITextField事件。 这将导致委托方法被调用两次(一次由协议定义,另一次由addTarget调用)。

通过(错误地)将UIControl事件连接到该方法,它被调用的参数与方法参数不匹配。 UIControl事件处理方法(其中shouldChangeCharactersInRange不)具有这些forms:

 - (void)methodName; - (void)methodName:(id)sender; - (void)methodName:(id)sender withEvent:(UIEvent *)event; 

有关详细信息,请参阅cocoa目标行动和iPhone应用程序开发讲座4 。

删除addTarget行来解决。


分别:

  • 是不是将0.0设置为使控件不可见?
  • 为什么userInteractionEnabled设置为NO?
  • 显式调用retain,调用addSubView,调用release,然后设置属性(即使它工作)不是通常的做事方式。 删除保留并将addSubView和release移动到最后。