UITextField rightViewMode无法正常工作

时间:2013-04-10 17:42:25

标签: ios uitextfield

我需要在UITextField上创建一个自定义清除按钮,所以我使用的是rightView。代码如下:

 UIImage *clearImage = [[UIImage imageNamed:@"search-clear.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(0.0,0.0, 0.0, 0.0)];
    UIImageView *clearImageView = [[UIImageView alloc]initWithImage:clearImage];

    UIButton *clearButton = [UIButton buttonWithType:UIButtonTypeCustom];
    clearButton.frame = clearImageView.frame;
    [clearButton setBackgroundImage:clearImage forState:UIControlStateNormal];
    clearButton.backgroundColor = [UIColor clearColor];

    self.emailTextField.rightViewMode = UITextFieldViewModeWhileEditing;
    self.emailTextField.rightView = clearButton;
    self.emailTextField.clearButtonMode = UITextFieldViewModeNever;

但是,该按钮未在正确的时间显示。它显示文本字段仅在文本长度为0时处于焦点。一旦我开始输入它就会消失。我需要弄清楚如何替换和复制清除按钮,以便在字符串至少为1个字符时显示。

1 个答案:

答案 0 :(得分:0)

你不能同时显示两者,但你可以这样做

UITextField * textfield = [[UITextField alloc] initWithFrame:CGRectMake(10, 100, 300, 40)];
[textfield setBorderStyle:UITextBorderStyleRoundedRect];

UIImageView * imgvw = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"search.jpeg"]];
[imgvw setFrame:CGRectMake(0, 0, 30, 30)];

[textfield setRightView:imgvw];
[textfield setRightViewMode:UITextFieldViewModeUnlessEditing];
[textfield setClearButtonMode:UITextFieldViewModeWhileEditing];

[self.view addSubview:textfield];