rightViewMode奇怪的行为

rightViewMode奇怪的行为

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

问题描述

我添加一个自定义清除按钮(UIButton)到UITextField作为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:


  • 在集中和无文字时显示

  • 在集中和打字时显示

  • >
  • 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.

推荐答案

这修复了错误:

- (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
的子类中,var _setupClearButtonMode设置为init 。

In your subclass of UITextFieldwith the var _setupClearButtonMode set on init.

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

09-02 08:13