17

我可以更改 textField 上 clearButtonMode 的颜色吗?

theTextField.clearButtonMode = UITextFieldViewModeWhileEditing

显示一个灰色的 x 以删除 textField,

但是我可以用白色显示这个按钮吗?

谢谢

4

5 回答 5

32

在这种情况下,您需要创建自己的清晰按钮图像。我建议拍摄清除按钮的屏幕截图并在 Photoshop 中进行编辑。

您可以获取该图像并创建具有图像尺寸的 UIButton。从那里您可以将其设置为 UITextField 的 rightView。像这样:

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setImage:[UIImage imageNamed:@"clear_button.png"] forState:UIControlStateNormal];
[button setFrame:CGRectMake(0.0f, 0.0f, 15.0f, 15.0f)]; // Required for iOS7
theTextField.rightView = button;
theTextField.rightViewMode = UITextFieldViewModeWhileEditing;

我在没有语法检查的情况下输入了它,所以你需要在运行它之前检查它。您还需要将 clear_button.png 替换为您的图像名称。

您还需要编写自己的方法来清除文本字段。

于 2012-04-23T02:47:39.250 回答
8

一种更简洁的方法是使用此方法在 UITextField 上实现一个类别:

- (void)modifyClearButtonWithImage:(UIImage *)image {
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setImage:image forState:UIControlStateNormal];
    [button setFrame:CGRectMake(0.0f, 0.0f, 15.0f, 15.0f)];
    [button addTarget:self action:@selector(clear:) forControlEvents:UIControlEventTouchUpInside];
    self.rightView = button;
    self.rightViewMode = UITextFieldViewModeWhileEditing;
}

-(IBAction)clear:(id)sender{
    self.text = @"";
}
于 2014-11-13T21:06:33.683 回答
7

斯威夫特版本:

extension UITextField {

    func modifyClearButtonWithImage(image : UIImage) {
        let clearButton = UIButton(type: .Custom)
        clearButton.setImage(image, forState: .Normal)
        clearButton.frame = CGRectMake(0, 0, 40, 40)
        clearButton.contentMode = .ScaleAspectFit
        clearButton.addTarget(self, action: #selector(UITextField.clear(_:)), forControlEvents: .TouchUpInside)
        self.rightView = clearButton
        self.rightViewMode = .WhileEditing
    }

    func clear(sender : AnyObject) {
        self.text = ""
    }

}
于 2016-10-03T12:22:30.273 回答
5

斯威夫特 4.1 版本

extension UITextField {
    func modifyClearButtonWithImage(image : UIImage) {
        let clearButton = UIButton(type: .custom)
        clearButton.setImage(image, for: .normal)
        clearButton.frame = CGRect(x: 0, y: 0, width: 40, height: 40)
        clearButton.contentMode = .scaleAspectFit
        clearButton.addTarget(self, action: #selector(UITextField.clear(sender:) ), for: .touchUpInside)
        self.rightView = clearButton
        self.rightViewMode = .whileEditing
    }

    @objc func clear(sender : AnyObject) {
        self.text = ""
        sendActions(for: .editingChanged)
    }
}
于 2018-07-11T11:40:01.290 回答
3

在您配置 textField 时,请使用:

let clearButton : UIButton = textField.value(forKey: "_clearButton") as! UIButton
let image = UIImage(named: "ClearWhite")

clearButton.setImage(image, for: .normal)
clearButton.backgroundColor = UIColor.clear
于 2016-11-15T05:36:22.917 回答