更改 appDelegate 中所有文本字段的 UITextField 占位符颜色

Changing UITextField Placeholder Color for ALL textfields in appDelegate

我知道您可以使用以下代码更改占位符文本:

mailTextField.attributedPlaceholder = NSAttributedString(string: "Email", attributes: [NSAttributedString.Key.foregroundColor : UIColor.black])

不幸的是,我有很多看起来应该都一样的文本字段。因此,为每个文本字段复制粘贴上面的代码非常烦人。

今天我发现如果您希望 UIElement 的外观始终保持不变,您可以在 appDelegate 中使用 appearance() 更改它。以下代码非常适合标签:

UILabel.appearance().textColor = Colors.greyLabel

但是当我尝试为文本字段占位符执行此操作时,它不起作用。

感谢您的帮助。

您可以创建自定义 class,它是 UITextField 的子class 作为

import Foundation
import UIKit

class CustomTextField:UITextField{

    override init(frame: CGRect) {
        super.init(frame: frame)
        setProperties()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setProperties()
    }

    func setProperties(){

        backgroundColor = UIColor.white
        textAlignment = .left
        textColor = .black
        font = UIFont.systemFont(ofSize: 15)
        borderStyle = .roundedRect
        if let placeholder = self.placeholder {
            self.attributedPlaceholder = NSAttributedString(string:placeholder, attributes: [NSAttributedString.Key.foregroundColor: UIColor.green])
        }
    }
}

如果您正在使用故事板,那么您可以将该自定义 class 分配给 UITextField

并以编程方式

var mailTextField = CustomTextField()

您可以使用 ֿappearanceWhenContainedInInstancesOfClasses 但它从 iOS 9.

开始可用

示例:

UILabel.appearanceWhenContainedInInstancesOfClasses([UITextField.self]).textColor = UIColor.redColor()’