【问题标题】:Using a UIButton inside a UITextField as a clear button在 UITextField 中使用 UIButton 作为清除按钮
【发布时间】:2013-09-12 07:08:34
【问题描述】:

我想做的是在 UITextField 中做一个自定义清除按钮,目前除了最后一部分外,我已经完成了所有工作。这是让它执行明确的行动。但是,我无法弄清楚如何才能清除它,只是它所在的 textField。

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    [textField setTextColor:[UIColor colorWithRed:0.56f green:0.56f blue:0.56f alpha:1.00f]];
    [textField setFont:[UIFont systemFontOfSize:14]];
    textField.background = [UIImage imageNamed:@"whiteCell"];

    UIButton *btnColor = [UIButton buttonWithType:UIButtonTypeCustom];
    [btnColor addTarget:self action:@selector(clearText:) forControlEvents:UIControlEventTouchUpInside];
    btnColor.frame = CGRectMake(0, 0, 25, 25);
    [btnColor setBackgroundImage:[UIImage imageNamed:@"clearBut"] forState:UIControlStateNormal];
    textField.rightView = btnColor;
    textField.rightViewMode = UITextFieldViewModeAlways;
    [textField addSubview:btnColor];


    return YES;
}

这就是我在 textField 中创建按钮的方式,并且它仅在编辑时显示,如您所见,我将其调用 clearText 但是我不确定如何发送当前的 textField 名称我我将在clearText 电话中被清除。

我知道我可以做到这一点,并为我的每个文本字段单独定义它,但我确信有一种更简单的方法可以解决这个问题,我只是还没有意识到。

【问题讨论】:

    标签: ios objective-c uibutton uitextfield


    【解决方案1】:

    我建议继承UITextField。这将不允许您在 Storyboard 中布置按钮,但在代码中或作为 .nib 文件应该可以工作。当然,您可以在情节提要中使用 UITextfield 子类。

    在子类中添加一个UIButton 作为子视图并在其操作方法调用中: self.text = @""

    如果您还有其他问题,请告诉我。

    【讨论】:

      【解决方案2】:

      鉴于您的按钮已作为子视图添加到文本字段中,您可以访问按钮超级视图属性中的文本字段:

      - (void) clearText:(UIButton*)sender
      {
          UITextField* textField = (UITextField*)sender.superview;
          textField.text = nil;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-03-08
        • 1970-01-01
        • 2020-03-27
        • 1970-01-01
        • 1970-01-01
        • 2011-02-25
        • 1970-01-01
        相关资源
        最近更新 更多