Change of UITextField placeholder color

后端 未结 13 1523
别跟我提以往
别跟我提以往 2021-01-30 06:09

How to dynamically change placeholder color of the UITextField? This is always the same system color.

No option in xib editor.

13条回答
  •  [愿得一人]
    2021-01-30 06:46

    This is an improved version of the extension provided by @Medin Piranej above (good idea by the way!). This version avoids an endless cycle if you try to get the placeHolderTextColor and prevents crashes if the color set is nil.

    public extension UITextField {
    
    @IBInspectable public var placeholderColor: UIColor? {
        get {
            if let attributedPlaceholder = attributedPlaceholder, attributedPlaceholder.length > 0 {
                var attributes = attributedPlaceholder.attributes(at: 0,
                                                                  longestEffectiveRange: nil,
                                                                  in: NSRange(location: 0, length: attributedPlaceholder.length))
                return attributes[NSForegroundColorAttributeName] as? UIColor
            }
            return nil
        }
        set {
            if let placeholderColor = newValue {
                attributedPlaceholder = NSAttributedString(string: placeholder ?? "",
                                                           attributes:[NSForegroundColorAttributeName: placeholderColor])
            } else {
                // The placeholder string is drawn using a system-defined color.
                attributedPlaceholder = NSAttributedString(string: placeholder ?? "")
            }
        }
    }
    

    }

提交回复
热议问题