带有自定义rightView的UITextField中的宽度问题

时间:2012-02-01 17:54:19

标签: iphone xcode uitextfield

我有一个UITextField(位于UITableViewCell内)UIButton作为自定义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;

显示文本字段时,未按预期处理触摸:

  • 如果我触摸按钮,则会触发。
  • 如果我触摸靠近按钮左边缘的区域(但在其边界之外),按钮仍然会被触发。
  • 如果我想在文本字段中编辑文本而不是触发按钮,我必须再向左触摸。

如果我将设备旋转到横向模式,事情会变得更糟。在这种情况下,按钮左侧仍然触发按钮的区域较宽,并且该区域左侧有一个间隙,它不执行任何操作 - 按钮未被触发且文本未被编辑。在这种情况下,我必须向左移动以编辑文本。

仅当字段中的当前文本很短时才会发生这种情况。如果文本填充文本字段,则按预期处理触摸(触摸按钮左侧任何位置都以纵向和横向编辑文本)。

我试图覆盖textRectForBoundseditingRectForBoundsrightViewRectForBounds。我确认它们已被调用并返回正确的值,但它们不会更改任何内容(只要返回值正确)。

有什么想法吗?

2 个答案:

答案 0 :(得分:5)

我在使用rightView时遇到了类似的问题,似乎阻止了部分文本字段接受输入。我的rightView不是一个按钮所以我只是将它的userInteractionEnabled设置为NO,文本字段开始在整个区域再次接触到触摸。

由于你有一个按钮作为rightView,这可能没什么用。但我们的例子之间的另一个相似之处是两个rightViews的宽度都很小。也许rightView不喜欢宽度< X。

答案 1 :(得分:0)

您是否为TableViewCell设置了任何自动调整大小属性?尝试添加:

[cell setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight];

并且textField和按钮设置UIViewAutoresizingFlexibleTopMargin选项,如下所示:

[textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];

[button setAutoresizingMask: UIViewAutoresizingFlexibleTopMargin];
相关问题