OGeek|极客世界-中国程序员成长平台

标题: ios - 在 UITextField 中使用 UIButton 作为清除按钮 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 14:20
标题: ios - 在 UITextField 中使用 UIButton 作为清除按钮

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

- (BOOL)textFieldShouldBeginEditingUITextField *)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 actionselector(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 但是我不确定如何发送我在 clearText 调用中要清除的当前文本字段名称。

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



Best Answer-推荐答案


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

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

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

关于ios - 在 UITextField 中使用 UIButton 作为清除按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18687315/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4