3

I need to make a custom clear button on a UITextField, so I am using the rightView. Code is below:

 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;

However, the button is not showing up at the correct times. It shows when the text field is in focus only with text length 0. As soon as I start typing it disappears. I need to figure out how to replace and duplicate the clear button, so that it shows when the string is at least 1 character.

JeffN
  • 1,575
  • 15
  • 26
  • Could you provide some screenshots? – Undo Apr 10 '13 at 17:45
  • http://gyazo.com/fce8bd7995851c8545c5f26a2f61fda4 – JeffN Apr 10 '13 at 17:46
  • http://gyazo.com/50aa6697331dd436faabcededcb2896f – JeffN Apr 10 '13 at 17:46
  • Look at the view hierarchy in the Xcode debugger to see what is happening. My guess is that the TextView is making itself front most. use `po [[UIWindow keyWindow] recursiveDescription]` to display the view hierarchy. – zaph Apr 10 '13 at 17:54
  • I cannot check right now, does this line necessary? `self.emailTextField.clearButtonMode = UITextFieldViewModeNever;` – Ossir Apr 10 '13 at 17:54
  • @Zaph, the background is clear, it isn't being covered, checked view hierarchy. I only want the button to show up when editing, same as the normal clear button. – JeffN Apr 10 '13 at 18:00
  • @Ossir, this is necessary to removed the default clear button – JeffN Apr 10 '13 at 18:00
  • @DCS123, actually it has been described already, here is possible solution http://stackoverflow.com/questions/7401263/uitextfield-rightviewmode-odd-behaviour – Ossir Apr 11 '13 at 07:28

1 Answers1

0

you can't display both at the same time , but you can do it like this

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];
devios1
  • 36,899
  • 45
  • 162
  • 260
Shaik Riyaz
  • 11,204
  • 7
  • 53
  • 70