简体   繁体   中英

Prevent UILabel text color change from overriding placeholder text color change in swift

I'm trying to make global color changes to an iOS app. I'm running into an issue where changes to UILabel.appearance().textColor propagate to UITextField placeholder text. The solutions that I've seen for this problem involve setting attributed strings or digging into private members of UITextField. How can I globally change the color of UILabel text color and also the placeholder text on a text field? I've tried the code below, but I end up with all green text.

UILabel.appearance().textColor = UIColor.greenColor()

// UITextField placeholder color
UILabel.appearanceWhenContainedInInstancesOfClasses([UITextField.self]).textColor = UIColor.cyanColor()

There is no way to specify placeholder text color using UIAppearance. (Only properties declared with UI_APPEARANCE_SELECTOR are available that way.) Your safest option is to use a UITextField subclass; here's one to make the color manageable in Interface Builder.

@IBDesignable class PCTextField: UITextField {
    @IBInspectable var placeholderColor: UIColor = UIColor.redColor() {
        didSet {
            if let placeholder = self.placeholder {
                let colorAttribute = [NSForegroundColorAttributeName: placeholderColor]
                attributedPlaceholder = NSAttributedString(string: placeholder, attributes: colorAttribute)
            }
        }
    }
}

If you're doing your color changes in code, then assigning placeholderColor from an NSUserDefaults setting would fit in reasonably smoothly with UIAppearance based management.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM