How to I stop a UIButton (being used as a custom clear button) resigning a UITextField as first responser?

StackOverflow https://stackoverflow.com/questions/15043422

Question

I'd need to create a custom clear button for a UITextField (because of my color scheme). I'm using the following code (where the class is a UITextField descendent):

UIButton *clearButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
[clearButton setImage:[UIImage imageNamed:@"ClearButton.png"] forState:UIControlStateNormal];
[self setRightView:clearButton];
[self setRightViewMode:UITextFieldViewModeNever];
[clearButton addTarget:self action:@selector(clear:) forControlEvents:UIControlEventTouchUpInside];

This works OK, mostly. The problem is that clicking on the clear button causes the UITextField to resign first responder status (i.e. the keyboard disappears). I'd like the UITextField to retain focus.

I tried just restoring the first responder status in the clear button's action, but, if the UITextField is in a UITableView - and is scrolled - this causes some undesirable scrolling in the table as the keyboard closes and opens.

I could use a UIImageView instead of a UIButton, but then I don't get the visual "pulse" as the button is tapped.

So, is there a way of having the UITextField retain first responder status when the button is pressed?

I'm developing an iPhone app using iOS 6.

[NB: The "clear:" action target just empties the text field, but, anyway, my problem occurs even if I don't set a target.]

Was it helpful?

Solution 2

Found the reason. I have a gesture recognizer that is used to handle closing the keyboard when the user taps the "background". That was being activated when the user click the close button on the text field.

I ended up implementing:

gestureRecognizer:shouldReceiveTouch:

to filter out the clear button.

OTHER TIPS

Maybe i dont understand your question but i think the problem could be on that, that you want to make first responder on textField which is not visible on your tableView. And this couldn't happen. You have to first show row contain your textField and than you can make it as first responder:

NSIndexPath *scrollIndexPath = [NSIndexPath indexPathForRow:yourIndex inSection:0];
[self.tableView scrollToRowAtIndexPath:scrollIndexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];

and than:

[self.textField becomeFirstResponder];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top