Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I change the color of a UITextField clearButton?

I would like to change the color of the clearButton that appaers when you are writting on a UItextField. Any suggestion? I am not an advanced interface developer and I have no idea of how to do it.

like image 718
sergiocg90 Avatar asked Mar 28 '12 20:03

sergiocg90


2 Answers

You should create your own UIButton (with image, you'll need a png of you desiderated button), instance it and put this button in the rightView of your UITextField.

CGFloat myWidth = 26.0f;
CGFloat myHeight = 30.0f;
UIButton *myButton = [[UIButton alloc] initWithFrame:CGRectMake(0.0f, 0.0f, myWidth, myHeight)];
[myButton setImage:[UIImage imageNamed:@"myButtonImage"] forState:UIControlStateNormal];
[myButton setImage:[UIImage imageNamed:@"myButtonImage"] forState:UIControlStateHighlighted];

[myButton addTarget:self action:@selector(doClear:) forControlEvents:UIControlEventTouchUpInside];

myTextField.rightView = myButton;
myTextField.rightViewMode = UITextFieldViewModeUnlessEditing;

You could need to refine alignments using (these are example values):

myButton.imageEdgeInsets = UIEdgeInsetsMake(0, -10, 0, 0);

Then, you will need to implement method -(void) doClear(id)sender; that will clear your textfield.

like image 161
Giorgio Marziani de Paolis Avatar answered Nov 06 '22 01:11

Giorgio Marziani de Paolis


Swift 4

I used Giorgio's answer and this is what I went with :

let height = textField.bounds.height / 3
let width = height + 10
let rect = CGRect(x: 0, y: 0, width: width, height: height)

let myButton = UIButton(frame: rect)

myButton.setImage(UIImage(named: "clear button white"), for: .normal)

textField.rightView = myButton
textField.rightViewMode = .always

myButton.imageEdgeInsets = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5)

The normal one : enter image description here

This one : enter image description here

like image 2
Guillaume Ramey Avatar answered Nov 06 '22 02:11

Guillaume Ramey