Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Displaying both a right view and a clear button in UITextField

After adding a right view to a UITextField, I am finding that it refuses to display both the right view and the clear button (having both rightViewMode and clearButtonMode set to UITextFieldViewModeAlways). I see the right view but the clear button is no longer displayed. I made sure that they don't overlap by having overriden clearButtonRectForBounds and clearButtonRectForBounds, to no avail. And if I use the leftView instead of rightView, then no such issue occurs and both the left view and the clear button are displayed.

So although it does not appear to be stated in the documentation, it looks to me like the clear button is only displayed when the right view isn't displayed (and when the text property isn't a blank string). Is this correct and does anyone have a reliable workaround? In the meantime I believe I am stuck with having to create a UIView that overlays my right view on top of a UITextField in order to get what I though I'd be getting from UITextField alone.

like image 795
Clafou Avatar asked Aug 03 '12 12:08

Clafou


2 Answers

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];
like image 104
Shaik Riyaz Avatar answered Sep 18 '22 18:09

Shaik Riyaz


Yes you are right. UITextfield has properties like left and right view. If you use clear button it overlaps rightview.

Form Apple doc http://developer.apple.com/library/ios/#DOCUMENTATION/UIKit/Reference/UITextField_Class/Reference/UITextField.html

If your overlay view does not overlap any other sibling views, it receives touch events like any other view. If you specify a control for your view, that control tracks and sends actions as usual. If an overlay view overlaps the clear button, however, the clear button always takes precedence in receiving events. By default, the right overlay view does overlap the clear button.

But like the name says it is a view. So you can create your own view which has 2 buttons on it and set rightview of the textfield. If you wish, you can use delegate methods of the textfield to make your buttons appear and dissapear from the view.

like image 20
Mert Avatar answered Sep 17 '22 18:09

Mert