iphone - UITextFieldDelegate问题

标签 iphone ios ipad

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

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”的运行时类型要么是 nil,要么是 NSCFString,如下所示:

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

当我编辑字符串时一切正常。

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

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

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

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

在某种程度上,更改协议(protocol)成员的声明会影响行为。

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

有什么想法吗?

最佳答案

UITextField 将自动调用 shouldChangeCharactersInRange 委托(delegate)方法(通过设置其 delegate 属性)。 UITextField 还可以调用其他委托(delegate)方法(如果您已实现)。

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

通过(错误地)将 UIControl 事件连接到该方法,会使用与该方法的参数不匹配的参数来调用它。 UIControl 事件处理方法(shouldChangeCharactersInRange 不是)具有以下形式:

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

参见 Cocoa Target-ActioniPhone App Development Lecture 4了解详情。

删除要修复的 addTarget 行。

<小时/> 分别:

  • 将 alpha 设置为 0.0 不会使控件不可见吗?
  • 为什么 userInteractionEnabled 设置为 NO?
  • 显式调用retain、调用addSubView、调用release,然后设置属性(即使它有效)并不是通常的处理方式。去掉retain,将addSubView和release移到最后。

关于iphone - UITextFieldDelegate问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5823560/

相关文章:

iphone - 与 iPhone 相比,XIB 中的对象显示位置不同(包含屏幕截图)

objective-c - TableView 数据在模拟器上不可见

iphone - 是否可以在不使用XCode创建新项目的情况下将通用应用程序更改为仅限iPad的应用程序?

ios - iOS : How to communicate with other Controller?

ios - 无需通过 AppStore 安装 iOS 应用程序

ios - iPhone 无法通过 WiFi 连接到本地 HTTP 服务器

ios - 使用 resizableImageWithCapInsets 将拉伸(stretch)的 UIImage 设置为 UILabel 的背景

ios - 将 Unmanaged<AnyObject> 与 nil 进行比较

ios - Objective-c 中 UIImageView 的动画

iphone - 如何绘制心率图表?