如何更改 UITextField 上清除按钮的色调

How to change the tint color of the clear button on a UITextField

我的 UITextfield 上有一个 auto-generated 清除按钮,默认为蓝色。我无法将色调颜色更改为白色。我试过修改storyboard和代码都没有成功,我不想使用自定义图片。

如何在不使用自定义图像的情况下更改默认的清除按钮色调颜色?

您无法执行此操作的原因是清晰的按钮图像没有着色。它们只是普通图像。

清除按钮是 UITextField 内部的一个按钮。像任何按钮一样,它可以有图像,而且确实如此。特别是,它有 两张 图像:一张用于正常状态,一张用于突出显示状态。 OP 反对的蓝色是突出显示的图像,可以在出现清除按钮时通过 运行 此代码捕获它:

    let tf = self.tf // the text view
    for sv in tf.subviews as! [UIView] {
        if sv is UIButton {
            let b = sv as! UIButton
            if let im = b.imageForState(.Highlighted) {
                // im is the blue x
            }
        }
    }

截取后会发现是一张14x14的双分辨率tiff图片,这里是:

理论上,您可以将图像更改为不同的颜色,并且可以将其指定为文本视图的清除按钮的高亮状态图像。但实际上这并不容易做到,因为按钮并不总是存在;当它不存在时你不能引用它(它不仅仅是不可见的;它实际上根本不是视图层次结构的一部分,所以没有办法访问它)。

而且没有UITextFieldAPI自定义清除按钮

因此,最简单的解决方案是建议 here:创建一个带有自定义普通图像和高亮图像的按钮,并将其作为 UITextField 的 rightView 提供。然后将 clearButtonMode 设置为从不(因为您使用的是正确的视图)并将 rightViewMode 设置为您喜欢的任何值。

当然,您随后必须检测到点击此按钮并通过清除文本字段的文本进行响应;但这很容易做到,留作 reader.

的练习。

给你!

一个 TintTextField。

不使用自定义图像,或添加按钮等

class TintTextField: UITextField {

     var tintedClearImage: UIImage?

     required init(coder aDecoder: NSCoder) {
       super.init(coder: aDecoder)
       self.setupTintColor()
     }

     override init(frame: CGRect) {
       super.init(frame: frame)
       self.setupTintColor()
     }

     func setupTintColor() {
       self.borderStyle = UITextField.BorderStyle.roundedRect
       self.layer.cornerRadius = 8.0
       self.layer.masksToBounds = true
       self.layer.borderColor = self.tintColor.cgColor
       self.layer.borderWidth = 1.5
       self.backgroundColor = .clear
       self.textColor = self.tintColor
     }

    override func layoutSubviews() {
        super.layoutSubviews()
        self.tintClearImage()
    }

    private func tintClearImage() {
        for view in subviews {
            if view is UIButton {
                let button = view as! UIButton
                if let image = button.image(for: .highlighted) {
                    if self.tintedClearImage == nil {
                        tintedClearImage = self.tintImage(image: image, color: self.tintColor)
                    }
                    button.setImage(self.tintedClearImage, for: .normal)
                    button.setImage(self.tintedClearImage, for: .highlighted)
                }
            }
        }
    }

    private func tintImage(image: UIImage, color: UIColor) -> UIImage {
        let size = image.size

        UIGraphicsBeginImageContextWithOptions(size, false, image.scale)
        let context = UIGraphicsGetCurrentContext()
        image.draw(at: .zero, blendMode: CGBlendMode.normal, alpha: 1.0)

        context?.setFillColor(color.cgColor)
        context?.setBlendMode(CGBlendMode.sourceIn)
        context?.setAlpha(1.0)

        let rect = CGRect(x: CGPoint.zero.x, y: CGPoint.zero.y, width: image.size.width, height: image.size.height)
        UIGraphicsGetCurrentContext()?.fill(rect)
        let tintedImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        return tintedImage ?? UIImage()
    }
 }

根据@Mikael Hellman 的回复,我已经为 Objective-C 准备了类似的 UITextField 子类实现。唯一的区别是我允许为正常和突出显示状态使用不同的颜色。

.h 文件

#import <UIKit/UIKit.h>


@interface TextFieldTint : UITextField

-(void) setColorButtonClearHighlighted:(UIColor *)colorButtonClearHighlighted;
-(void) setColorButtonClearNormal:(UIColor *)colorButtonClearNormal;

@end

.m 文件

#import "TextFieldTint.h"

@interface TextFieldTint()

@property (nonatomic,strong) UIColor *colorButtonClearHighlighted;
@property (nonatomic,strong) UIColor *colorButtonClearNormal;

@property (nonatomic,strong) UIImage *imageButtonClearHighlighted;
@property (nonatomic,strong) UIImage *imageButtonClearNormal;


@end

@implementation TextFieldTint


-(void) layoutSubviews
{
    [super layoutSubviews];
    [self tintButtonClear];
}

-(void) setColorButtonClearHighlighted:(UIColor *)colorButtonClearHighlighted
{
    _colorButtonClearHighlighted = colorButtonClearHighlighted;
}

-(void) setColorButtonClearNormal:(UIColor *)colorButtonClearNormal
{
    _colorButtonClearNormal = colorButtonClearNormal;
}

-(UIButton *) buttonClear
{
    for(UIView *v in self.subviews)
    {
        if([v isKindOfClass:[UIButton class]])
        {
            UIButton *buttonClear = (UIButton *) v;
            return buttonClear;
        }
    }
    return nil;
}



-(void) tintButtonClear
{
    UIButton *buttonClear = [self buttonClear];

    if(self.colorButtonClearNormal && self.colorButtonClearHighlighted && buttonClear)
    {
        if(!self.imageButtonClearHighlighted)
        {
            UIImage *imageHighlighted = [buttonClear imageForState:UIControlStateHighlighted];
            self.imageButtonClearHighlighted = [[self class] imageWithImage:imageHighlighted
                                                                  tintColor:self.colorButtonClearHighlighted];
        }
        if(!self.imageButtonClearNormal)
        {
            UIImage *imageNormal = [buttonClear imageForState:UIControlStateNormal];
            self.imageButtonClearNormal = [[self class] imageWithImage:imageNormal
                                                             tintColor:self.colorButtonClearNormal];
        }

        if(self.imageButtonClearHighlighted && self.imageButtonClearNormal)
        {
            [buttonClear setImage:self.imageButtonClearHighlighted forState:UIControlStateHighlighted];
            [buttonClear setImage:self.imageButtonClearNormal forState:UIControlStateNormal];
        }
    }
}


+ (UIImage *) imageWithImage:(UIImage *)image tintColor:(UIColor *)tintColor
{
    UIGraphicsBeginImageContextWithOptions(image.size, NO, 0.0);
    CGContextRef context = UIGraphicsGetCurrentContext();

    CGRect rect = (CGRect){ CGPointZero, image.size };
    CGContextSetBlendMode(context, kCGBlendModeNormal);
    [image drawInRect:rect];

    CGContextSetBlendMode(context, kCGBlendModeSourceIn);
    [tintColor setFill];
    CGContextFillRect(context, rect);

    UIImage *imageTinted  = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return imageTinted;
}
@end

您可以使用 KVO 访问清除按钮并更新它:

    UIButton *clearButton = [myTextField valueForKey:@"_clearButton"]
    if([clearButton respondsToSelector:@selector(setImage:forState:)]){

        //ensure that the app won't crash in the future if _clearButton reference changes to a different class instance
        [clearButton setImage:[UIImage imageNamed:@"MyImage.png"] forState:UIControlStateNormal];

    }

注意:此解决方案不是面向未来的 - 如果 Apple 更改清除按钮的实现,这将正常停止工作。

如果您在应用中使用 UIAppearance,则可以在运行时为清除按钮设置 tintColor。

let textField = UITextField.appearance()
textField.tintColor = .green

在启动时,我们在 AppDelegate 中调用一个 class 函数,该函数具有许多其他控件,这些控件在其中配置了 .appearance()

假设你的 class 设置你的应用程序的外观被称为 Beautyify 你会创建这样的东西:

@objc class Beautify: NSObject {
    class func applyAppearance() {
        let tableViewAppearance = UITableView.appearance()
        tableViewAppearance.tintColor = .blue

        let textField = UITextField.appearance()
        textField.tintColor = .green
    }
}

然后在AppDelegate里面didFinishLaunchingWithOptions直接调用即可。

Beautify.applyAppearance()

这是在您的应用程序中同时配置事物外观的好方法。

在 Swift 中,您可以编写扩展名并在项目中的任何文本字段上使用。

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

    @objc func clear(_ sender : AnyObject) {
    if delegate?.textFieldShouldClear?(self) == true {
        self.text = ""
        sendActions(for: .editingChanged)
    }
}
}

它可能比评分最高的答案更容易,适用于 iOS 7 及更高版本。

@interface MyTextField

@end

@implementation MyTextField

- (void)layoutSubviews {
    [super layoutSubviews];

    for (UIView *subView in self.subviews) {
        if ([subView isKindOfClass:[UIButton class]]) {
            UIButton *button = (UIButton *)subView;
            [button setImage:[[button imageForState:UIControlStateNormal] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate]
                    forState:UIControlStateNormal];
            button.tintColor = self.tintColor;
        }
    }
}

@end

这对我有用 objective-C。我从关于这个主题的其他线程中提取了一些片段并提出了这个解决方案:

UIButton *btnClear = [self.textFieldUserID valueForKey:@"clearButton"];
[btnClear setImage:[UIImage imageNamed:@"facebookLoginButton"] forState:UIControlStateNormal];

这是Swift 3 更新的解决方案:

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

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

尽情享受 ;)

在研究了所有的答案和可能性之后,我找到了这个简单直接的解决方案。

-(void)updateClearButtonColor:(UIColor *)color ofTextField:(UITextField *)textField {

    UIButton *btnClear = [textField valueForKey:@"_clearButton"];
    UIImage * img = [btnClear imageForState:UIControlStateNormal];

    if (img) {
        UIImage * renderingModeImage = [img imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
        [btnClear setImage:renderingModeImage forState:UIControlStateNormal];
        //-- Add states you want to update
        [btnClear setImage:renderingModeImage forState:UIControlStateSelected];
    }

    [btnClear setTintColor:color];
}


[self updateClearButtonColor:[UIColor whiteColor] ofTextField:self.textField];

在 SWIFT 3 中:这对我有用

    if let clearButton = self.textField.value(forKey: "_clearButton") as? UIButton {
        // Create a template copy of the original button image
        let templateImage =  clearButton.imageView?.image?.withRenderingMode(.alwaysTemplate)

        // Set the template image copy as the button image
        clearButton.setImage(templateImage, for: .normal)
        clearButton.setImage(templateImage, for: .highlighted)

        // Finally, set the image color
        clearButton.tintColor = .white
    }

matt 上面的回答是正确的。 UITextField 中的清除按钮如果不显示则不存在。可以尝试在 UITextField 执行其 layoutSubviews 后立即访问它并检查按钮是否存在。 最简单的方法是子类化 UITextField,覆盖 layoutSubviews,如果按钮是第一次显示,则存储它的原始图像供以后使用,然后在任何后续显示期间应用色调。

下面我将向您展示如何使用扩展来执行此操作,因为通过这种方式您可以将自定义色调应用于任何 UITextField,包括嵌套在就绪 类 中的那些,例如 UISearchBar。

祝你玩得开心,喜欢就点个赞:)

Swift 3.2

这里是主要的扩展:

import UIKit

extension UITextField {

    private struct UITextField_AssociatedKeys {
        static var clearButtonTint = "uitextfield_clearButtonTint"
        static var originalImage = "uitextfield_originalImage"
    }

    private var originalImage: UIImage? {
        get {
            if let cl = objc_getAssociatedObject(self, &UITextField_AssociatedKeys.originalImage) as? Wrapper<UIImage> {
                return cl.underlying
            }
            return nil
        }
        set {
            objc_setAssociatedObject(self, &UITextField_AssociatedKeys.originalImage, Wrapper<UIImage>(newValue), .OBJC_ASSOCIATION_RETAIN)
        }
    }

    var clearButtonTint: UIColor? {
        get {
            if let cl = objc_getAssociatedObject(self, &UITextField_AssociatedKeys.clearButtonTint) as? Wrapper<UIColor> {
                return cl.underlying
            }
            return nil
        }
        set {
            UITextField.runOnce
            objc_setAssociatedObject(self, &UITextField_AssociatedKeys.clearButtonTint, Wrapper<UIColor>(newValue), .OBJC_ASSOCIATION_RETAIN)
            applyClearButtonTint()
        }
    }

    private static let runOnce: Void = {
        Swizzle.for(UITextField.self, selector: #selector(UITextField.layoutSubviews), with: #selector(UITextField.uitextfield_layoutSubviews))
    }()

    private func applyClearButtonTint() {
        if let button = UIView.find(of: UIButton.self, in: self), let color = clearButtonTint {
            if originalImage == nil {
                originalImage = button.image(for: .normal)
            }
            button.setImage(originalImage?.tinted(with: color), for: .normal)
        }
    }

    func uitextfield_layoutSubviews() {
        uitextfield_layoutSubviews()
        applyClearButtonTint()
    }

}

以下是上述代码中使用的其他片段:

任何你想访问对象的东西的漂亮包装器:

class Wrapper<T> {
    var underlying: T?

    init(_ underlying: T?) {
        self.underlying = underlying
    }
}

用于查找任何类型的嵌套子视图的少数扩展:

extension UIView {

    static func find<T>(of type: T.Type, in view: UIView, includeSubviews: Bool = true) -> T? where T: UIView {
        if view.isKind(of: T.self) {
            return view as? T
        }
        for subview in view.subviews {
            if subview.isKind(of: T.self) {
                return subview as? T
            } else if includeSubviews, let control = find(of: type, in: subview) {
                return control
            }
        }
        return nil
    }

}

UIImage 应用色调的扩展

extension UIImage {

    func tinted(with color: UIColor) -> UIImage? {
        UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale)
        color.set()
        self.withRenderingMode(.alwaysTemplate).draw(in: CGRect(origin: CGPoint(x: 0, y: 0), size: self.size))

        let result = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        return result
    }

}

...最后是 Swizzling 的东西:

class Swizzle {

    class func `for`(_ className: AnyClass, selector originalSelector: Selector, with newSelector: Selector) {
        let method: Method = class_getInstanceMethod(className, originalSelector)
        let swizzledMethod: Method = class_getInstanceMethod(className, newSelector)
        if (class_addMethod(className, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod))) {
            class_replaceMethod(className, newSelector, method_getImplementation(method), method_getTypeEncoding(method))
        } else {
            method_exchangeImplementations(method, swizzledMethod)
        }
    }

}

对于Swift 4,将其添加到 UITextField 的子类中:

import UIKit

class CustomTextField: UITextField {

    override func layoutSubviews() {
        super.layoutSubviews()

        for view in subviews {
            if let button = view as? UIButton {
                button.setImage(button.image(for: .normal)?.withRenderingMode(.alwaysTemplate), for: .normal)
                button.tintColor = .white
            }
        }
    }
}

您可以使用我的库 LSCategories 一行完成:

[textField lsSetClearButtonWithColor:[UIColor redColor] mode:UITextFieldViewModeAlways];

它不使用任何私有 api,它不在 UITextField 子视图层次结构中搜索原始 UIButton,并且它不需要将 UITextField 子类化为此处的其他一些答案。相反,它使用 rightView 属性 来模拟系统清除按钮,因此您无需担心如果 Apple 更改某些内容,它会在未来停止工作。它也适用于 Swift。

Swift 4,这对我有用(将 tintColor 更改为您自己的颜色):

var didSetupWhiteTintColorForClearTextFieldButton = false

private func setupTintColorForTextFieldClearButtonIfNeeded() {
    // Do it once only
    if didSetupWhiteTintColorForClearTextFieldButton { return }

    guard let button = yourTextField.value(forKey: "_clearButton") as? UIButton else { return }
    guard let icon = button.image(for: .normal)?.withRenderingMode(.alwaysTemplate) else { return }
    button.setImage(icon, for: .normal)
    button.tintColor = .white
    didSetupWhiteTintColorForClearTextFieldButton = true
}

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    setupTintColorForTextFieldClearButtonIfNeeded()
}

需要在 viewDidLayoutSubviews() 中调用它,以确保它最终被调用,因为有不同的 clearButtonMode 情况(alwayswhileEditing 等.).我相信这些按钮是懒惰创建的。所以在 viewDidLoad() 中调用它大多不起作用。

Swift4、干净简洁的Subclass

import UIKit

class CustomTextField: UITextField {
    override func layoutSubviews() {
        super.layoutSubviews()
        for view in subviews where view is UIButton {
            (view as! UIButton).setImage(<MY_UIIMAGE>, for: .normal)
        }
    }
}

您可以使用自定义图标,它适用于 iOS11,

searchBar.setImage(UIImage(named: "ic_clear"), for: .clear, state: .normal)

创建此方法。

func configureClearButtonColor() {

    guard let clearButton = textField.value(forKey: "_clearButton") as? UIButton else {
        return
    }
    let templateImage = clearButton.imageView?.image?.withRenderingMode(.alwaysTemplate)
    clearButton.setImage(templateImage, for: .normal)
    clearButton.setImage(templateImage, for: .highlighted)
    clearButton.tintColor = .white
}

并在 textFieldDidEndEditing 调用方法时实现您的 UITextFieldDelegate。在创建一些文本之前更改您的图像。

func textFieldDidEndEditing(_ textField: UITextField) {
    configureClearButtonColor()
}

详情

  • Xcode 版本 10.1 (10B61)
  • Swift 4.2

解决方案

import UIKit

extension UISearchBar {

    func getTextField() -> UITextField? { return value(forKey: "searchField") as? UITextField }

    func setClearButton(color: UIColor) {
        getTextField()?.setClearButton(color: color)
    }
}

extension UITextField {

    private class ClearButtonImage {
        static private var _image: UIImage?
        static private var semaphore = DispatchSemaphore(value: 1)
        static func getImage(closure: @escaping (UIImage?)->()) {
            DispatchQueue.global(qos: .userInteractive).async {
                semaphore.wait()
                DispatchQueue.main.async {
                    if let image = _image { closure(image); semaphore.signal(); return }
                    guard let window = UIApplication.shared.windows.first else { semaphore.signal(); return }
                    let searchBar = UISearchBar(frame: CGRect(x: 0, y: -200, width: UIScreen.main.bounds.width, height: 44))
                    window.rootViewController?.view.addSubview(searchBar)
                    searchBar.text = "txt"
                    searchBar.layoutIfNeeded()
                    _image = searchBar.getTextField()?.getClearButton()?.image(for: .normal)
                    closure(_image)
                    searchBar.removeFromSuperview()
                    semaphore.signal()
                }
            }
        }
    }

    func setClearButton(color: UIColor) {
        ClearButtonImage.getImage { [weak self] image in
            guard   let image = image,
                    let button = self?.getClearButton() else { return }
            button.imageView?.tintColor = color
            button.setImage(image.withRenderingMode(.alwaysTemplate), for: .normal)
        }
    }

    func getClearButton() -> UIButton? { return value(forKey: "clearButton") as? UIButton }
}

完整样本

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        let textField = UITextField(frame: CGRect(x: 20, y: 20, width: 200, height: 44))
        view.addSubview(textField)
        textField.backgroundColor = .lightGray
        textField.clearButtonMode = .always
        textField.setClearButton(color: .red)

        let searchBar = UISearchBar(frame: CGRect(x: 20, y: 80, width: 200, height: 44))
        view.addSubview(searchBar)
        searchBar.backgroundColor = .lightGray
        searchBar.setClearButton(color: .red)
    }
}

结果

我尝试了很多答案,直到找到基于@Mikael Hellman 解决方案的解决方案。此解决方案使用 Swift 4.2.

思路相同:

Using no custom image, or added buttons etc.

并使用扩展 UITextField.

的自定义 class
class TintClearTextField: UITextField {

    private var updatedClearImage = false

    override func layoutSubviews() {
        super.layoutSubviews()
        tintClearImage()
    }

    private func tintClearImage() {
        if updatedClearImage { return }

        if let button = self.value(forKey: "clearButton") as? UIButton,
            let image = button.image(for: .highlighted)?.withRenderingMode(.alwaysTemplate) {
            button.setImage(image, for: .normal)
            button.setImage(image, for: .highlighted)
            button.tintColor = .white

            updatedClearImage = true
        }
    }
}

您不需要 updatedClearImage,但请记住,您将在每个字符添加中执行所有逻辑。

我什至不需要设置 tintColor 来获得我正在寻找的结果。在设置为您的颜色之前尝试对该行进行注释。

如果看起来不像您想要的,请将 .white 更改为您想要的颜色,仅此而已。

PS.: 我有一个字段已经填充在我的初始屏幕中,对于这唯一的一个,tintColor 的颜色变化发生在显示默认项目颜色后几毫秒,比如"glitch"。我无法做得更好,但由于我没有使用 tintColor,这对我来说没问题。

希望对您有所帮助:)

想法是通过按键clearButton获取清除按钮,然后使用alwaysTemplate模式重新渲染清除图像。

[Swift4.2] 刚刚在此处对 UITextField 进行了扩展:

extension UITextField {
    var clearButton: UIButton? {
        return value(forKey: "clearButton") as? UIButton
    }

    var clearButtonTintColor: UIColor? {
        get {
            return clearButton?.tintColor
        }
        set {
            let image =  clearButton?.imageView?.image?.withRenderingMode(.alwaysTemplate)
            clearButton?.setImage(image, for: .normal)
            clearButton?.tintColor = newValue
        }
    }
}

但此解决方案的问题是,在您调用设置色调时,清除按钮的图像是 nil

所以每个人都在使用RxSwift来观察清除按钮中的图像。

import RxSwift

extension UITextField {
    var clearButton: UIButton? {
        return value(forKey: "clearButton") as? UIButton
    }

    var clearButtonTintColor: UIColor? {
        get {
            return clearButton?.tintColor
        }
        set {
            _ = rx.observe(UIImage.self, "clearButton.imageView.image")
                .takeUntil(rx.deallocating)
                .subscribe(onNext: { [weak self] _ in
                    let image = self?.clearButton?.imageView?.image?.withRenderingMode(.alwaysTemplate)
                    self?.clearButton?.setImage(image, for: .normal)
                })
            clearButton?.tintColor = newValue
        }
    }
}

修改@3vangelos的解决方案,绕过这个for循环

for view in subviews where view is UIButton {
        (view as! UIButton).setImage(<MY_UIIMAGE>, for: .normal)
    }

我的修改:-

class CustomTextField:UITextField { 
override func layoutSubviews()
    {super.layoutSubviews()
    let clearButton = self.value(forKey: "clearButton") as? UIButton
    clearButton?.setImage(#imageLiteral(resourceName: "icons8-cancel.pdf"), for: .normal)
    clearButton?.tintColor = UIColor(<YOUR_COLOR>)
}

可以在 UISearchBar 中使用相同的解决方案并添加一些代码:-

 override func viewWillAppear(_ animated: Bool)
{
    super.viewWillAppear(animated)
if let textField = agentsSearchBar.value(forKey: "searchField") as? UITextField
    {
let clearButton = textField.value(forKey: "clearButton") as? UIButton
clearButton?.setImage(#imageLiteral(resourceName: "icons8-cancel.pdf"), for: .normal)
clearButton?.tintColor = UIColor(<YOUR_COLOR>)
} }

图片(icons8-cancel.pdf)可以在 https://icons8.com/icon/set/clear-button/ios7# and added to your image assets with the following attributes

喜欢@Brody Robertson 的回答,这里是 Swift 5 版本,它适用于我:

let textField = UITextField()
if let button = textField.value(forKey: "clearButton") as? UIButton {
  button.tintColor = .white
  button.setImage(UIImage(named: "yourImage")?.withRenderingMode(.alwaysTemplate), for: .normal)
}

注意:你需要用你的图标替换yourImage,或者如果你的目标是iOS13.0或以上,你可以替换方法UIImage(named:)UIImage(systemName: "xmark.circle.fill")。 Apple 在 iOS 13.0 或更高版本中为您准备了这个清晰的图标。我希望这个能帮上忙!祝你好运!

Swift 5 解:

   if let clearButton = yourTextField.value(forKey: "_clearButton") as? UIButton {
       let templateImage = clearButton.imageView?.image?.withRenderingMode(.alwaysTemplate)
       clearButton.setImage(templateImage, for: .normal)
       clearButton.tintColor = .darkGray
   }