ios UITextField清除按钮模式颜色

ozxc1zmp  于 2022-11-19  发布在  iOS
关注(0)|答案(6)|浏览(433)

是否可以更改textField上clearButtonMode的颜色?

theTextField.clearButtonMode = UITextFieldViewModeWhileEditing

显示一个x即灰暗颜色删除的textField、
但是我可以用白色来显示这个按钮吗?
感谢

1qczuiv0

1qczuiv01#

在这种情况下,你需要创建自己的清除按钮图像。我建议你截图清除按钮,然后在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。
您还需要编写自己的方法来清除文本字段。

relj7zay

relj7zay2#

一种更简洁的方法是使用以下方法在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 = @"";
}
zazmityj

zazmityj3#

Swift版本:

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 = ""
    }

}
mznpcxlj

mznpcxlj4#

Swift 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)
    }
}
iezvtpos

iezvtpos5#

在配置textField时,请用途:

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

clearButton.setImage(image, for: .normal)
clearButton.backgroundColor = UIColor.clear
r7s23pms

r7s23pms6#

用户界面样式= .dark

相关问题