【问题标题】:Width issue in a UITextField with custom rightView具有自定义 rightView 的 UITextField 中的宽度问题
【发布时间】:2023-03-07 02:02:02
【问题描述】:

我有一个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。我验证了它们被调用并返回正确的值,但它们没有改变任何东西(只要返回值正确)。

有什么想法吗?

【问题讨论】:

  • 你解决过这个问题吗?我现在遇到了同样的问题。

标签: iphone xcode uitextfield


【解决方案1】:

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

由于您有一个按钮作为 rightView,因此这可能无济于事。但我们的示例之间的另一个相似之处是,两个 rightView 的宽度都很小。也许 rightView 不喜欢宽度

【讨论】:

  • 宾果游戏!做到了。我一直在试图弄清楚我在做什么来阻止输入(我使用的是 leftView 和 leftViewMode)。在我的填充视图上设置 userInteractionEnabled 似乎可以解决它。谢谢!
【解决方案2】:

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

[cell setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight];

文本字段和按钮设置UIViewAutoresizingFlexibleTopMargin 选项如下:

[textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];

[button setAutoresizingMask: UIViewAutoresizingFlexibleTopMargin];

【讨论】:

  • 没有必要为 UITableViewCell 设置 autoResizingMask,它继承自 UITableView(我确实尝试过,没有改变)。 UITextField 已经有一个自动调整大小的掩码(参见代码),并且按钮不应调整大小,因为它是一个基于图像的按钮。