UITextField rightViewMode 奇怪的行为 [英] UITextField rightViewMode odd behaviour

查看:16
本文介绍了UITextField rightViewMode 奇怪的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在向 UITextField 添加一个自定义清除按钮 (UIButton) 作为 rightView,但是我发现 viewMode 上有一些奇怪的行为.尽管设置了视图模式,但它似乎不像正常的清除按钮那样显示.示例代码如下:

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:

  • 聚焦时显示,无文字
  • 在专注和打字时显示
  • 没有焦点时隐藏

但是,如果文本字段已经有内容,并且您将焦点切换到它,则清除按钮不会显示.要让它再次显示,您必须删除所有文本,并来回切换焦点.

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.

推荐答案

这修复了错误:

- (BOOL)becomeFirstResponder
{
    BOOL ret = YES ;

    ret = [super becomeFirstResponder] ;

    if( ret && ( _setupClearButtonMode == UITextFieldViewModeWhileEditing ) )
        self.rightViewMode = UITextFieldViewModeAlways ;

    return ret ;
}

- (BOOL)resignFirstResponder
{
    BOOL ret = YES ;

    ret = [super resignFirstResponder] ;

    if( ret && ( _setupClearButtonMode == UITextFieldViewModeWhileEditing ) )
        self.rightViewMode = UITextFieldViewModeWhileEditing ;

    return ret ;
}

在 UITextField 的子类中在 init 上设置了 var _setupClearButtonMode.

In your subclass of UITextField with the var _setupClearButtonMode set on init.

这篇关于UITextField rightViewMode 奇怪的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆