3

我需要在 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 个字符时显示。

4

1 回答 1

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];
于 2013-11-04T10:37:06.763 回答