UITextField rightViewMode 奇怪的行为
我将自定义清除按钮(UIButton)添加到 UITextField 作为 rightView,但是我发现 viewMode 上有一些奇怪的行为。尽管设置了查看模式,但它似乎不像正常的清除按钮那样显示。下面的示例代码:
UITextField *f = [[[UITextField alloc] init] autorelease];
f.frame = CGRectMake(0, 0, 300, 44);
f.backgroundColor = [UIColor clearColor];
f.textColor = [UIColor whiteColor];
f.clearButtonMode = UITextFieldViewModeNever;
UIImage *image = [UIImage imageNamed:@"Image.png"];
UIButton *b = [UIButton buttonWithType:UIButtonTypeCustom];
b.frame = CGRectMake(0, 0, image.size.width, image.size.height);
[b setImage:image forState:UIControlStateNormal];
f.rightView = b;
f.rightViewMode = UITextFieldViewModeWhileEditing;
该按钮在以下状态下正确显示:
- 获得焦点且无文本时
- 显示 获得焦点并键入时显示
- 没有焦点时隐藏
但是,如果文本字段已有内容,并且您将焦点切换到该文本字段,则清除按钮不会显示。要使其再次显示,您必须删除所有文本,并来回切换焦点。
我还没有发现其他人遇到这个问题,所以我已经在这个问题上摸索了一段时间了。非常感谢任何光线脱落。
I'm adding a custom clear button (UIButton) to a UITextField as the rightView, however I've found there's some weird behaviour on the viewMode. It doesn't seem to display as the normal clear button does, despite the view mode being set. Example code below:
UITextField *f = [[[UITextField alloc] init] autorelease];
f.frame = CGRectMake(0, 0, 300, 44);
f.backgroundColor = [UIColor clearColor];
f.textColor = [UIColor whiteColor];
f.clearButtonMode = UITextFieldViewModeNever;
UIImage *image = [UIImage imageNamed:@"Image.png"];
UIButton *b = [UIButton buttonWithType:UIButtonTypeCustom];
b.frame = CGRectMake(0, 0, image.size.width, image.size.height);
[b setImage:image forState:UIControlStateNormal];
f.rightView = b;
f.rightViewMode = UITextFieldViewModeWhileEditing;
The button displays correctly in the following states:
- Shows while focused and no text
- Shows while focused and typing
- Hides when no focus
However, if the textfield already has content, and you switch focus to it the clear button does not show. To get it to show again you must delete all text, and switch focus back and forth.
I haven't found anyone else with this problem, so have been scratching my head on this one for a while. Any light shedding very much appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这修复了错误:
在 UITextField 的子类中
在 init 上设置 var _setupClearButtonMode。
This fixes the bug :
In your subclass of UITextField
with the var _setupClearButtonMode set on init.
我最近遇到了同样的问题,最终将正确的视图模式设置为 UITextFieldViewModeAlways 并在需要时手动显示/隐藏该按钮(创建监视文本字段状态的代理委托,设置按钮的可见性并将消息传递给实际委托)。
I recently ran into the same problem and ended up setting right view mode to UITextFieldViewModeAlways and manually showing/hiding that button when it's needed (made proxy delegate which monitored text field state, set button's visibility and passed messages to actual delegate).
简单的代码解决这个问题
Simple code for solve this problem