Kautham Murugan Kautham Murugan - 7 months ago 30
Swift Question

How to set a global Place holder colour for a UITextField for the whole app in swift?

I am creating a app in which i use several

UITextfield
's. I know how to change the
placeholder
colour of a single text field.

textField.attributedPlaceholder = NSAttributedString(string: "Username", attributes: [NSForegroundColorAttributeName: UIColor.redColor()])
.

But i want to change the placeholder colour of all the
UITextField
s in the whole app. My app has more than 50
UIViewControllers
and more than 25 of them has textFields(2 to 22 per screen). I want a code that can be used globally in one place so that i don't need to go to every view controller and change it manually.

If you have any other alternatives to make the job done please let me know.

I am using
xcode 7.1.1
swift 2.0


Update:
For default the Placeholder colour is set to light grey colour. Is there any way for us to tweak that default behaviour and change it to any other colour?

How can we access this default code and change it?

Answer

Create the extension method

extension String {

func toAttributedString(font font:UIFont!, kerning: CGFloat!, color:UIColor!) -> NSAttributedString {
    return NSAttributedString(string: self as String, font: font, kerning: kerning, color: color)!
}
}

extension NSAttributedString {

convenience init?(string text:String, font:UIFont!, kerning: CGFloat!, color:UIColor!) {
    self.init(string: text, attributes: [NSKernAttributeName:kerning, NSFontAttributeName:font, NSForegroundColorAttributeName:color])
}
}

Example usage

/ Example Usage
var testString: String = "Hi Kautham"

var testAttributedString: NSAttributedString = testString.toAttributedString(font: UIFont.boldSystemFontOfSize(20), kerning: 2.0, color: UIColor.whiteColor())


let label = UILabel(frame: CGRect(x: 50, y: 50, width: 200, height: 20))

label.attributedText = testAttributedString
 self.view.addSubview(label)
Comments