Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Width issue in a UITextField with custom rightView

I have a UITextField (placed inside a UITableViewCell) that has a UIButton as a custom rightView:

    UITextField *textField = [[[UITextField alloc] initWithFrame:CGRectMake(10.0, 1.0, cell.bounds.size.width - 20.0, 31.0)] autorelease];
    textField.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.bounds = CGRectMake(0.0, 0.0, 27.0, 31.0); // Probably not needed, doesn't change anything
    button.frame = CGRectMake(0.0, 0.0, 27.0, 31.0);
    [button setImage:[UIImage imageNamed:@"27x31.png"] forState:UIControlStateNormal];
    textField.rightView = button;                                
    textField.rightViewMode = UITextFieldViewModeUnlessEditing;

When the text field is shown, touches are not handled as expected:

  • If I touch the button, it is triggered.
  • If I touch an area close to the left edge of the button (but outside its bounds), the button is still triggered.
  • If I want to edit the text in the text field rather than trigger the button, I have to touch further to the left.

Things get worse if I rotate the device to landscape mode. In this case, the area to the left of the button that still triggers the button is wider, and there's a gap to the left of this area that does nothing - the button is not triggered and the text is not edited. I have to move a considerable way to the left to edit the text in this situation.

This only happens if the current text in the field is short. If the text fills the text field, touches are handled as expected (touches anywhere to the left of the button edit the text in both portrait and landscape).

I tried to override textRectForBounds, editingRectForBounds and rightViewRectForBounds. I verified that they are called and return the correct values, but they don't change anything (as long as the return values are correct).

Any ideas?

like image 216
Amiram Stark Avatar asked Feb 01 '12 17:02

Amiram Stark


1 Answers

I had a similar issue with a rightView that seemed to prevent a portion of the textfield from accepting input. My rightView was not a button so I simply set it's userInteractionEnabled to NO and the textfield started receiving touches again across its entire area.

Since you have a button as a rightView this might not help much. But another similarity between our examples was that both rightViews had a small width. Perhaps the rightView doesn't like having a width < x.

like image 104
Ben Packard Avatar answered Oct 11 '22 17:10

Ben Packard