Search code examples
iosswiftswift4

textfield placeholder centered and also change color


I want to make my UITextField placeholder to center aligned and also change the placeholderColor. I have already make text center aligned using this

extension String {
    func attributedString(aligment: NSTextAlignment) -> NSAttributedString {
        return NSAttributedString(text: self, aligment: aligment)
    }
}

extension NSAttributedString {
    convenience init(text: String, aligment: NSTextAlignment) {
        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.alignment = aligment
        self.init(string: text, attributes: [NSAttributedStringKey.paragraphStyle: paragraphStyle])
    }
}

and call above extension method like below

textField.attributedPlaceholder = NSAttributedString(text: text, aligment: .left)

But I am not able to change the color of placeholder. How should I change my placeholder color? Any help is appreciated.


Solution

  • Try using modified extension like below..

    extension NSAttributedString 
        {
            convenience init(text: String, aligment: NSTextAlignment, color:UIColor) {
                let paragraphStyle = NSMutableParagraphStyle()
                paragraphStyle.alignment = aligment
                self.init(string: text, attributes: [NSAttributedStringKey.paragraphStyle: paragraphStyle, NSAttributedStringKey.foregroundColor:color])
            }
        }
    

    Usage

    textField.attributedPlaceholder = NSAttributedString(text: text, aligment: .left, color:UIColor.red)