Change of UITextField placeholder color - ios

How to dynamically change placeholder color of the UITextField?
This is always the same system color.
No option in xib editor.

From Docs
#property(nonatomic, copy) NSAttributedString *attributedPlaceholder
This property is nil by default. If set, the placeholder string is
drawn using a 70% grey color and the remaining style information
(except the text color) of the attributed string. Assigning a new
value to this property also replaces the value of the placeholder
property with the same string data, albeit without any formatting
information. Assigning a new value to this property does not affect
any other style-related properties of the text field.
Objective-C
NSAttributedString *str = [[NSAttributedString alloc] initWithString:#"Some Text" attributes:#{ NSForegroundColorAttributeName : [UIColor redColor] }];
self.myTextField.attributedPlaceholder = str;
Swift
let str = NSAttributedString(string: "Text", attributes: [NSForegroundColorAttributeName:UIColor.redColor()])
myTextField.attributedPlaceholder = str
Swift 4
let str = NSAttributedString(string: "Text", attributes: [NSAttributedString.Key.foregroundColor: UIColor.red])
myTextField.attributedPlaceholder = str

_placeholderLabel.textColor
In swift
myTextField.attributedPlaceholder =
NSAttributedString(string: "placeholder", attributes:[NSForegroundColorAttributeName : UIColor.redColor()])
Objective-C
UIColor *color = [UIColor grayColor];
nameText.attributedPlaceholder =
[[NSAttributedString alloc]
initWithString:#"Full Name"
attributes:#{NSForegroundColorAttributeName:color}];
P.S Copied 3 different answers from Stackoverflow.

Use below code
[YourtextField setValue:[UIColor colorWithRed:97.0/255.0 green:1.0/255.0 blue:17.0/255.0 alpha:1.0] forKeyPath:#"_placeholderLabel.textColor"];

First add this extension
extension UITextField{
#IBInspectable var placeHolderTextColor: UIColor? {
set {
let placeholderText = self.placeholder != nil ? self.placeholder! : ""
attributedPlaceholder = NSAttributedString(string:placeholderText, attributes:[NSForegroundColorAttributeName: newValue!])
}
get{
return self.placeHolderTextColor
}
}
}
Then you can change placeholder text color via storyboard or by just setting it like this :
textfield.placeHolderTextColor = UIColor.red

I use this in SWIFT:
myTextField.attributedPlaceholder =
NSAttributedString(string: "placeholder", attributes: [NSForegroundColorAttributeName : UIColor.redColor()])
It seems that this works for others... I have no idea why it haven't worked for me before... maybe some project settings. Thanks for the comments. Currently I have no way how to test it again.
Obsolete:
But I don't know why, text is applied correctly, but placeholder color remains same (black/gray).
--iOS8

Try this:
NSAttributedString *strUser = [[NSAttributedString alloc] initWithString:#"Username" attributes:#{ NSForegroundColorAttributeName : [UIColor whiteColor] }];
NSAttributedString *strPassword = [[NSAttributedString alloc] initWithString:#"Password" attributes:#{ NSForegroundColorAttributeName : [UIColor whiteColor] }];
self.username.attributedPlaceholder = strUser;
self.password.attributedPlaceholder = strPassword;

You can use the following code
[txtUsername setValue:[UIColor darkGrayColor] forKeyPath:#"_placeholderLabel.textColor"];

This solution works without any subclassing and without any private ivars:
#IBOutlet weak var emailTextField: UITextField! {
didSet {
if emailTextField != nil {
let placeholderText = NSLocalizedString("Tap here to enter", comment: "Tap here to enter")
let placeholderString = NSAttributedString(string: placeholderText, attributes: [NSForegroundColorAttributeName: UIColor(white: 0.66, alpha: 1.0)])
emailTextField.attributedPlaceholder = placeholderString
}
}
}

Try This.
UIColor *color = [UIColor redColor];
self.txtUsername.attributedPlaceholder = [[NSAttributedString alloc] initWithString:#"Your Placeholder Text" attributes:#{NSForegroundColorAttributeName:color}];

Swift 4
let placeholderColor = UIColor.red
self.passwordTextField?.attributedPlaceholder =
NSAttributedString(string:"placeholderText", attributes:
[NSAttributedStringKey.foregroundColor : placeholderColor])

#DogCoffee's answer in Swift would be
let placeholderAttrs = [ NSForegroundColorAttributeName : UIColor.redColor()]
let placeholder = NSAttributedString(string: "Some text", attributes: placeholderAttrs)
textField.attributedPlaceholder = placeholder

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 ?? "")
}
}
}
}

for swift 3 ,we can use this code for change the placeholder text color for UITextfield
let placeholderColor = UIColor.red
mytextField.attributedPlaceholder = NSAttributedString(string: mytextField.placeholder, attributes: [NSForegroundColorAttributeName : placeholderColor])

Related

UITextField attributedPlaceholder color and opacity in swift 4

I have custom textField which has #IBInspectable property placeHolderColor: UIColor and it works fine. I set it by:
attributedPlaceholder = NSAttributedString(string: placeHolder, attributes:[NSAttributedStringKey.foregroundColor: placeHolderColor])
How can I set programmatically an opacity value for this property only, not for normal text in my textfield ? I didn't find any matching NSAttributedStringKey to do this
UIColor class methods withAlphaComponent(alpha: ) to set a color alpha. read more
#IBInspectable var placeholderTextColor: UIColor? {
set {
guard let color = newValue else { return }
let placeholderText = self.placeholder ?? ""
attributedPlaceholder = NSAttributedString(string: placeholderText, attributes: [NSAttributedStringKey.foregroundColor: color.withAlphaComponent(alpha: self.alpha)])
}
get{
return self.placeholderTextColor
}
}
in Swift 4.2
attributedPlaceholder = NSAttributedString(string: placeholderText, attributes: [NSAttributedString.Key.foregroundColor: color.withAlphaComponent(self.alpha)])
SWIFT 5
I used this to change the color without inputing a new String for placeholder
textField.attributedPlaceholder = NSAttributedString(string: textField.text!, attributes:
[NSAttributedString.Key.foregroundColor: UIColor."Your preferred color"])

How to change UITextfield placeholder color and fontsize using swift 2.0?

How to change UITextfield placeholder & fontsize in SWIFT 2.0?
#1. set Placeholder textfield color Programmatically
var myMutableStringTitle = NSMutableAttributedString()
let Name = "Enter Title" // PlaceHolderText
myMutableStringTitle = NSMutableAttributedString(string:Name, attributes: [NSFontAttributeName:UIFont(name: "Georgia", size: 20.0)!]) // Font
myMutableStringTitle.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range:NSRange(location:0,length:Name.characters.count)) // Color
txtTitle.attributedPlaceholder = myMutableStringTitle
OR
txtTitle.attributedPlaceholder = NSAttributedString(string:"Enter Title", attributes: [NSForegroundColorAttributeName: yellowColor])
Note : Name is your placeholder of textField.
PlaceHolder TextFiled :
-------------------------------- OR -------------------------------------
#2. set Placeholder textfield color at runtime attribute
Set textfield placeHolder text Enter Title
Click on identity inspector of textfield property.
User Define Runtime Attributes, add color attributes
Key Path : _placeholderLabel.textColor
Type : Color
value : Your Color or RGB value
PlaceHolder TextFiled :
Updated for Swift 3
If you want to change the UITextField Placeholder color for Swift 3, use the following lines of code:
let yourTextFieldName = UITextField(frame: CGRect(x: 0, y: 0, width: 180, height: 21))
yourTextFieldName.attributedPlaceholder = NSAttributedString(string: "placeholder text", attributes: [NSForegroundColorAttributeName: UIColor.white])
Updated for Swift 5
For swift 5.0 use NSAttributedString.Key.foregroundColor instead of NSForegroundColorAttributeName
So, do it like so
textField.attributedPlaceholder = NSAttributedString(string: "placeholder text", attributes: [NSAttributedString.Key.foregroundColor: UIColor.white])
For swift 4 instead of
NSForegroundColorAttributeName
use
NSAttributedStringKey.foregroundColor
You can try with this sample code
let textFld = UITextField();
textFld.frame = CGRectMake(0,0, 200, 30)
textFld.center = self.view.center;
textFld.attributedPlaceholder = NSAttributedString(string:"Test Data for place holder", attributes:[NSForegroundColorAttributeName: UIColor.blueColor(),NSFontAttributeName :UIFont(name: "Arial", size: 10)!])
self.view.addSubview(textFld)
Placeholder for textfield Objective C
NSString* str = #"Placeholder text...";
NSRange range1 = [str rangeOfString:#"Placeholder text..."];
NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithString:str];
[attributedText setAttributes:#{
NSFontAttributeName:[UIFont fontWithName:customFont_NotoSans_Regular size:13.0]
}
range:range1];
[attributedText addAttribute:NSForegroundColorAttributeName value:[UIColor whiteColor] range:range1];
txtFld.font = [UIFont fontWithName:customFont_NotoSans_Regular size:13.0];
txtFld.keyboardType = UIKeyboardTypeDefault;
txtFld.attributedPlaceholder = attributedText;
It's easy to do with a subclass of UITextField.
Add placeholderColor property to easily set the color, and then observer changing of .placeholder to apply the color to it (with use of .attributedPlaceholder property)
var placeholderColor: UIColor = .lightGray
override var placeholder: String? {
didSet {
let attributes = [ NSAttributedString.Key.foregroundColor: placeholderColor ]
attributedPlaceholder = NSAttributedString(string: placeholder ?? "", attributes: attributes)
}
}
You do need to set the placeholder text programatically for the color to apply.
set Textfield placeholder
let leftBarButtonItem = UIBarButtonItem.init(image: UIImage(named:"ic_nav-bar_back.png"), landscapeImagePhone: nil, style: .plain, target: viewController, action: #selector(viewController.buttonClick(_:)))
leftBarButtonItem.imageInsets = UIEdgeInsets(top: 0, left: -15, bottom: 0, right: 0)
leftBarButtonItem.tintColor = UIColor(hex: 0xED6E19)
viewController.navigationItem.setLeftBarButton(leftBarButtonItem, animated: true)
A simple solution is override placeholder property in an UITextField extension. It will update color of placeholder whole project. You don't need to update your code in many places.
extension UITextField {
var placeholder: String? {
get {
attributedPlaceholder?.string
}
set {
guard let newValue = newValue else {
attributedPlaceholder = nil
return
}
let attributes: [NSAttributedString.Key: Any] = [.foregroundColor: Color.textFieldPlaceholder.color]
let attributedText = NSAttributedString(string: newValue, attributes: attributes)
attributedPlaceholder = attributedText
}
}
}
open your identity inspector by selecting text field and then put " placeholderLabel.textColor " in key path by pressing + button .
Give the type " Color " and in value select desired RGB color.
Swift 5
textfiled.attributedPlaceholder = NSAttributedString(string:NSLocalizedString("Input Group Name", comment: "Input Group Name"), attributes: [NSAttributedString.Key.foregroundColor: yourColor.withAlphaComponent(0.5)])

How can I set the attributed text while having no placeholder text?

Code that worked in Xcode 6.2 no longer works and I'm having trouble figuring out how to fix it. String attributes are now ignored unless I set default text. Here's what I've got right now:
let font = UIFont(name: "Arial-BoldMT", size: 42.0)!
let textStyle = NSMutableParagraphStyle.defaultParagraphStyle().mutableCopy() as! NSMutableParagraphStyle
textStyle.alignment = NSTextAlignment.Center
let textColor = UIColor.whiteColor()
var shadow = NSShadow()
shadow.shadowColor = UIColor.blackColor()
shadow.shadowOffset = CGSizeMake(2.0,2.0)
var attr = [String:NSObject]()
attr = [
NSFontAttributeName: font,
NSForegroundColorAttributeName: textColor,
NSParagraphStyleAttributeName: textStyle,
NSShadowAttributeName: shadow
]
let placeholderText = NSAttributedString(string: "", attributes: attr)
textView.attributedText = placeholderText
If you change the placeHolderText to NSAttributedString(string: " ", attributes: attr) you can then change the UITextView's text by changing its text property and the new text will have all the same attributes.
I hope that answers your question.

Changing Placeholder Text Color with Swift

I have a design that implements a dark blue UITextField, as the placeholder text is by default a dark grey colour I can barely make out what the place holder text says.
I've googled the problem of course but I have yet to come up with a solution while using the Swift language and not Obj-c.
Is there a way to change the placeholder text colour in a UITextField using Swift?
You can set the placeholder text using an attributed string. Just pass the color you want to the attributes parameter.
Swift 5:
let myTextField = UITextField(frame: CGRect(x: 0, y: 0, width: 200, height: 30))
myTextField.backgroundColor = .blue
myTextField.attributedPlaceholder = NSAttributedString(
string: "Placeholder Text",
attributes: [NSAttributedString.Key.foregroundColor: UIColor.white]
)
Swift 3:
myTextField.attributedPlaceholder = NSAttributedString(
string: "Placeholder Text",
attributes: [NSAttributedStringKey.foregroundColor: UIColor.white]
)
Older Swift:
myTextField.attributedPlaceholder = NSAttributedString(
string: "Placeholder Text",
attributes: [NSForegroundColorAttributeName: UIColor.white]
)
You can accomplish this quickly, without adding a line of code, using Interface Builder.
Select the UITextField and open the identity inspector on the right:
Click on the plus button and add a new runtime attribute:
placeholderLabel.textColor (Swift 4)
_placeholderLabel.textColor (Swift 3 or less)
Use Color as type and select the color.
That's it.
You wont see the result until you run your app again.
Create UITextField Extension like this:
extension UITextField{
#IBInspectable var placeHolderColor: UIColor? {
get {
return self.placeHolderColor
}
set {
self.attributedPlaceholder = NSAttributedString(string:self.placeholder != nil ? self.placeholder! : "", attributes:[NSAttributedString.Key.foregroundColor: newValue!])
}
}
}
And in your storyboard or .xib. You will see
In Swift 3.0, Use
let color = UIColor.lightText
textField.attributedPlaceholder = NSAttributedString(string: textField.placeholder, attributes: [NSForegroundColorAttributeName : color])
In Siwft 5.0 + Use
let color = UIColor.lightText
let placeholder = textField.placeholder ?? "" //There should be a placeholder set in storyboard or elsewhere string or pass empty
textField.attributedPlaceholder = NSAttributedString(string: placeholder, attributes: [NSAttributedString.Key.foregroundColor : color])
This code is working in Swift3:
yourTextFieldName .setValue(UIColor.init(colorLiteralRed: 80/255, green: 80/255, blue: 80/255, alpha: 1.0), forKeyPath: "_placeholderLabel.textColor")
let me know if you have any issue.
To set the placeholder color once for all the UITextField in your app you can do:
UILabel.appearanceWhenContainedInInstancesOfClasses([UITextField.self]).textColor = UIColor.redColor()
This will set the desired color for all TextField placeholders in the entire app. But it is only available since iOS 9.
There is no appearenceWhenContainedIn....() method before iOS 9 in swift but you can use one of the solutions provided here appearanceWhenContainedIn in Swift
In my case, I use Swift 4
I create extension for UITextField
extension UITextField {
func placeholderColor(color: UIColor) {
let attributeString = [
NSAttributedStringKey.foregroundColor: color.withAlphaComponent(0.6),
NSAttributedStringKey.font: self.font!
] as [NSAttributedStringKey : Any]
self.attributedPlaceholder = NSAttributedString(string: self.placeholder!, attributes: attributeString)
}
}
yourField.placeholderColor(color: UIColor.white)
Xcode 9.2 Swift 4
extension UITextField{
#IBInspectable var placeHolderColor: UIColor? {
get {
return self.placeHolderColor
}
set {
self.attributedPlaceholder = NSAttributedString(string:self.placeholder != nil ? self.placeholder! : "", attributes:[NSAttributedStringKey.foregroundColor: newValue!])
}
}
}
For Swift
Create UITextField Extension
extension UITextField{
func setPlaceHolderColor(){
self.attributedPlaceholder = NSAttributedString(string: self.placeholder!, attributes: [NSForegroundColorAttributeName : UIColor.white])
}
}
If Are you set from storyboard.
extension UITextField{
#IBInspectable var placeHolderColor: UIColor? {
get {
return self.placeHolderColor
}
set {
self.attributedPlaceholder = NSAttributedString(string:self.placeholder != nil ? self.placeholder! : "", attributes:[NSAttributedString.Key.foregroundColor : newValue!])
}
}
}
Swift 4 :
txtControl.attributedPlaceholder = NSAttributedString(string: "Placeholder String...",attributes: [NSAttributedStringKey.foregroundColor: UIColor.gray])
Objective-C :
UIColor *color = [UIColor grayColor];
txtControl.attributedPlaceholder = [[NSAttributedString alloc] initWithString:#"Placeholder String..." attributes:#{NSForegroundColorAttributeName: color}];
Here is my quick implementation for swift 4:
extension UITextField {
func placeholderColor(_ color: UIColor){
var placeholderText = ""
if self.placeholder != nil{
placeholderText = self.placeholder!
}
self.attributedPlaceholder = NSAttributedString(string: placeholderText, attributes: [NSAttributedStringKey.foregroundColor : color])
}
}
use like:
streetTextField?.placeholderColor(AppColor.blueColor)
hope it helps someone!
Swift 3 (probably 2), you can override didSet on placeholder in UITextField subclass to apply attribute on it, this way:
override var placeholder: String? {
didSet {
guard let tmpText = placeholder else {
self.attributedPlaceholder = NSAttributedString(string: "")
return
}
let textRange = NSMakeRange(0, tmpText.characters.count)
let attributedText = NSMutableAttributedString(string: tmpText)
attributedText.addAttribute(NSForegroundColorAttributeName , value:UIColor(white:147.0/255.0, alpha:1.0), range: textRange)
self.attributedPlaceholder = attributedText
}
}
I'm surprised to see how many poor solutions there are here.
Here is a version that will always work.
Swift 4.2
extension UITextField{
#IBInspectable var placeholderColor: UIColor {
get {
return self.attributedPlaceholder?.attribute(.foregroundColor, at: 0, effectiveRange: nil) as? UIColor ?? .lightText
}
set {
self.attributedPlaceholder = NSAttributedString(string: self.placeholder ?? "", attributes: [.foregroundColor: newValue])
}
}
}
TIP: If you change the placeholder text after setting the color- the color will reset.
For Swift 3 and 3.1 this works perfectly fine:
passField.attributedPlaceholder = NSAttributedString(string: "password", attributes: [NSForegroundColorAttributeName: UIColor.white])
For Swift 4.0, X-code 9.1 version or iOS 11 you can use following syntax to have different placeholder color
textField.attributedPlaceholder = NSAttributedString(string: "Placeholder Text", attributes: [NSAttributedStringKey.foregroundColor : UIColor.white])
Just write below code into Appdelegate's didFinishLaunchingWithOptions method use this if you want to change in the whole app written in Swift 4.2
UILabel.appearance(whenContainedInInstancesOf: [UITextField.self]).textColor = UIColor.white
Here am i writing all UIDesignable of UITextField. With the help of this code you can directly access it from UI file Inspector in storyboard
#IBDesignable
class CustomTextField: UITextField {
#IBInspectable var leftImage: UIImage? {
didSet {
updateView()
}
}
#IBInspectable var leftPadding: CGFloat = 0 {
didSet {
updateView()
}
}
#IBInspectable var rightImage: UIImage? {
didSet {
updateView()
}
}
#IBInspectable var rightPadding: CGFloat = 0 {
didSet {
updateView()
}
}
private var _isRightViewVisible: Bool = true
var isRightViewVisible: Bool {
get {
return _isRightViewVisible
}
set {
_isRightViewVisible = newValue
updateView()
}
}
func updateView() {
setLeftImage()
setRightImage()
// Placeholder text color
attributedPlaceholder = NSAttributedString(string: placeholder != nil ? placeholder! : "", attributes:[NSAttributedString.Key.foregroundColor: tintColor])
}
func setLeftImage() {
leftViewMode = UITextField.ViewMode.always
var view: UIView
if let image = leftImage {
let imageView = UIImageView(frame: CGRect(x: leftPadding, y: 0, width: 20, height: 20))
imageView.image = image
// Note: In order for your image to use the tint color, you have to select the image in the Assets.xcassets and change the "Render As" property to "Template Image".
imageView.tintColor = tintColor
var width = imageView.frame.width + leftPadding
if borderStyle == UITextField.BorderStyle.none || borderStyle == UITextField.BorderStyle.line {
width += 5
}
view = UIView(frame: CGRect(x: 0, y: 0, width: width, height: 20))
view.addSubview(imageView)
} else {
view = UIView(frame: CGRect(x: 0, y: 0, width: leftPadding, height: 20))
}
leftView = view
}
func setRightImage() {
rightViewMode = UITextField.ViewMode.always
var view: UIView
if let image = rightImage, isRightViewVisible {
let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 20, height: 20))
imageView.image = image
// Note: In order for your image to use the tint color, you have to select the image in the Assets.xcassets and change the "Render As" property to "Template Image".
imageView.tintColor = tintColor
var width = imageView.frame.width + rightPadding
if borderStyle == UITextField.BorderStyle.none || borderStyle == UITextField.BorderStyle.line {
width += 5
}
view = UIView(frame: CGRect(x: 0, y: 0, width: width, height: 20))
view.addSubview(imageView)
} else {
view = UIView(frame: CGRect(x: 0, y: 0, width: rightPadding, height: 20))
}
rightView = view
}
#IBInspectable public var borderColor: UIColor = UIColor.clear {
didSet {
layer.borderColor = borderColor.cgColor
}
}
#IBInspectable public var borderWidth: CGFloat = 0 {
didSet {
layer.borderWidth = borderWidth
}
}
#IBInspectable public var cornerRadius: CGFloat = 0 {
didSet {
layer.cornerRadius = cornerRadius
}
}
#IBInspectable public var bottomBorder: CGFloat = 0 {
didSet {
borderStyle = .none
layer.backgroundColor = UIColor.white.cgColor
layer.masksToBounds = false
// layer.shadowColor = UIColor.gray.cgColor
layer.shadowOffset = CGSize(width: 0.0, height: 1.0)
layer.shadowOpacity = 1.0
layer.shadowRadius = 0.0
}
}
#IBInspectable public var bottomBorderColor : UIColor = UIColor.clear {
didSet {
layer.shadowColor = bottomBorderColor.cgColor
layer.shadowOffset = CGSize(width: 0.0, height: 1.0)
layer.shadowOpacity = 1.0
layer.shadowRadius = 0.0
}
}
/// Sets the placeholder color
#IBInspectable var placeHolderColor: UIColor? {
get {
return self.placeHolderColor
}
set {
self.attributedPlaceholder = NSAttributedString(string:self.placeholder != nil ? self.placeholder! : "", attributes:[NSAttributedString.Key.foregroundColor: newValue!])
}
}
}
Use like this in Swift,
let placeHolderText = textField.placeholder ?? ""
let str = NSAttributedString(string:placeHolderText!, attributes: [NSAttributedString.Key.foregroundColor :UIColor.lightGray])
textField.attributedPlaceholder = str
In Objective C
NSString *placeHolder = [textField.placeholder length]>0 ? textField.placeholder: #"";
NSAttributedString *str = [[NSAttributedString alloc] initWithString:placeHolder attributes:#{ NSForegroundColorAttributeName : [UIColor lightGrayColor] }];
textField.attributedPlaceholder = str;
In my case, I had to make the placeholder into black color. The name of my UITextField is passwordText. Below code is tested in Swift 5 and is working fine for me. I also had an existing text for the corresponding placeholder.
let placeholderColor = UIColor.black
passwordText.attributedPlaceholder = NSAttributedString(string: passwordText.placeholder!, attributes: [NSAttributedString.Key.foregroundColor : placeholderColor])
crubio's answer update for Swift 4
Select the UITextField and open the identity inspector on the right:
Click on the plus button and add a new runtime attribute: placeholderLabel.textColor (instead of _placeholderLabel.textColor)
Use Color as type and select the color.
If you run your project, you will see the changes.
For swift 4.2 and above you can do it as below:
textField.attributedPlaceholder = NSAttributedString(string: "Placeholder Text", attributes: [NSAttributedString.Key.foregroundColor: UIColor.white])
In my case, I have done following:
extension UITextField {
#IBInspectable var placeHolderColor: UIColor? {
get {
if let color = self.attributedPlaceholder?.attribute(.foregroundColor, at: 0, effectiveRange: nil) as? UIColor {
return color
}
return nil
}
set (setOptionalColor) {
if let setColor = setOptionalColor {
let string = self.placeholder ?? ""
self.attributedPlaceholder = NSAttributedString(string: string , attributes:[NSAttributedString.Key.foregroundColor: setColor])
}
}
}
}
extension UITextField{
#IBInspectable var placeHolderColor: UIColor? {
get {
return self.placeHolderColor
}
set {
self.attributedPlaceholder = NSAttributedString(string:self.placeholder != nil ?
self.placeholder! : "",
attributes:[NSAttributedString.Key.foregroundColor : newValue!])
}
}
}
For Swift
func setPlaceholderColor(textField: UITextField, placeholderText: String) {
textField.attributedPlaceholder = NSAttributedString(string: placeholderText, attributes: [NSForegroundColorAttributeName: UIColor.pelorBlack])
}
You can use this;
self.setPlaceholderColor(textField: self.emailTextField, placeholderText: "E-Mail/Username")
It is more about personalize your textField but anyways I'll share this code got from another page and made it a little better:
import UIKit
extension UITextField {
func setBottomLine(borderColor: UIColor, fontColor: UIColor, placeHolderColor:UIColor, placeHolder: String) {
self.borderStyle = UITextBorderStyle.none
self.backgroundColor = UIColor.clear
let borderLine = UIView()
let height = 1.0
borderLine.frame = CGRect(x: 0, y: Double(self.frame.height) - height, width: Double(self.frame.width), height: height)
self.textColor = fontColor
borderLine.backgroundColor = borderColor
self.addSubview(borderLine)
self.attributedPlaceholder = NSAttributedString(
string: placeHolder,
attributes: [NSAttributedStringKey.foregroundColor: placeHolderColor]
)
}
}
And you can use it like this:
self.textField.setBottomLine(borderColor: lineColor, fontColor: fontColor, placeHolderColor: placeHolderColor, placeHolder: placeHolder)
Knowing that you have an UITextField connected to a ViewController.
Source: http://codepany.com/blog/swift-3-custom-uitextfield-with-single-line-input/
For Objective C:
UIColor *color = [UIColor colorWithRed:0.44 green:0.44 blue:0.44 alpha:1.0];
emailTextField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:#"Friend's Email" attributes:#{NSForegroundColorAttributeName: color}];
For Swift:
emailTextField.attributedPlaceholder = NSAttributedString(string: "Friend's Email",
attributes: [NSAttributedString.Key.foregroundColor: UIColor.white])
Objective C code for changing placeholder text color.
First import this objc/runtime class -
#import <objc/runtime.h>
then replace your textfield name -
Ivar ivar = class_getInstanceVariable([UITextField class], "_placeholderLabel");
UILabel *placeholderLabel = object_getIvar(YourTxtField, ivar);
placeholderLabel.textColor = [UIColor whiteColor];
for iOS13
+(void)ChangeplaceholderColor :(UITextField *)TxtFld andColor:(UIColor*)color {
NSMutableAttributedString *placeholderAttributedString = [[NSMutableAttributedString alloc] initWithAttributedString:TxtFld.attributedPlaceholder];
[placeholderAttributedString addAttribute:NSForegroundColorAttributeName value:color range:NSMakeRange(0, [placeholderAttributedString length])];
TxtFld.attributedPlaceholder = placeholderAttributedString;
}
Use this for adding an attributed placeholder:
let attributes : [String : Any] = [ NSForegroundColorAttributeName: UIColor.lightGray,
NSFontAttributeName : UIFont(name: "Helvetica Neue Light Italic", size: 12.0)!
]
x_textfield.attributedPlaceholder = NSAttributedString(string: "Placeholder Text", attributes:attributes)
For Swift 4
txtField1.attributedPlaceholder = NSAttributedString(string: "-", attributes: [NSAttributedStringKey.foregroundColor: UIColor.white])

Changing UITextField Placeholder font

I'm changing the placeholder text color with the following code, but when I try to add NSFontAttribute I get the compiler error "too many arguments to method call, expect 2 have 3"
UIColor *color = [UIColor blackColor];
_nameField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:#"Your Name" attributes:#{NSForegroundColorAttributeName: color},#{NSFontAttributeName:#"Roboto-Bold"}];
This Works Fine:
UIColor *color = [UIColor blackColor];
_nameField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:#"Your Name" attributes:#{NSForegroundColorAttributeName: color}];
Objective-C:
UIColor *color = [UIColor blackColor];
someUITextField.attributedPlaceholder =
[[NSAttributedString alloc] initWithString:#"Placeholder Text"
attributes:#{
NSForegroundColorAttributeName: color,
NSFontAttributeName : [UIFont fontWithName:#"Roboto-Bold" size:17.0]
}
];
(There are no brackets between literal dictionary key-value pairs.)
Swift:
let attributes = [
NSForegroundColorAttributeName: UIColor.blackColor(),
NSFontAttributeName : UIFont(name: "Roboto-Bold", size: 17)! // Note the !
]
someUITextField.attributedPlaceholder = NSAttributedString(string: "Placeholder Text", attributes:attributes)
Update for Swift 4.x:
textField.attributedPlaceholder = NSAttributedString(string: "Placeholder Text", attributes: [
.foregroundColor: UIColor.lightGray,
.font: UIFont.boldSystemFont(ofSize: 14.0)
])
For the convenience of swift people:
someTextField.attributedPlaceholder = NSAttributedString(string: "someString",
attributes:[NSForegroundColorAttributeName: UIColor.lightGrayColor(), NSFontAttributeName: PlaceHolderFont])
You should subclass UITextField, and override the method of:
- (void)drawPlaceholderInRect:(CGRect)rect;
Here is the implementation below:
- (void)drawPlaceholderInRect:(CGRect)rect {
NSDictionary *attributes = #{
NSForegroundColorAttributeName : [UIColor lightGrayColor],
NSFontAttributeName : [UIFont italicSystemFontOfSize:self.font.pointSize]
};
// center vertically
CGSize textSize = [self.placeholder sizeWithAttributes:attributes];
CGFloat hdif = rect.size.height - textSize.height;
hdif = MAX(0, hdif);
rect.origin.y += ceil(hdif/2.0);
[[self placeholder] drawInRect:rect withAttributes:attributes];
}
For more you can find click here
Appreciate #ddevaz answer.
UITextField Subclass solution
Above answer works perfect for UITextField. But when i use UITextField subclass and try to execute this method in it. Then its not working.
I found other solution only when you subclass UITextField. Override below method in your UITextField subclass and it will do job for you.
- (void) drawPlaceholderInRect:(CGRect)rect {
NSDictionary *attrDictionary = #{
NSForegroundColorAttributeName: [UIColor lightGrayColor],
NSFontAttributeName : [UIFont fontWithName:#"Menlo" size:17.0]
};
[[self placeholder] drawInRect:rect withAttributes:attrDictionary];
}
Working version for Swift 4
let attributes = [NSAttributedStringKey.foregroundColor: UIColor.black,
.font : UIFont.systemFont(ofSize: 14, weight: .regular)]
someTextfield.attributedPlaceholder = NSAttributedString(string: "Placeholder text", attributes:attributes)
Update for Swift 4
let attributes = [
NSAttributedStringKey.foregroundColor: .black,
NSAttributedStringKey.font : UIFont(name: "Your font name", size: 14)!
]
someTextfield.attributedPlaceholder = NSAttributedString(string: "Placeholder text", attributes:attributes)
Update for Swift 4.2 +
let attributes = [NSAttributedString.Key.foregroundColor: UIColor.black,
.font: UIFont.systemFont(ofSize: 14)]
searchTextField.attributedPlaceholder = NSAttributedString(string: "Placeholder text",
attributes: attributes)
Reference for more attribute Keys - NSAttributedString.Key
If you want to support both iOS 6 and previous versions then:
UIColor *placeholderColor = [UIColor lightTextColor];
UIFont *placeholderFont = [UIFont systemFontOfSize:[UIFont systemFontSize]];
if ([textField respondsToSelector:#selector(attributedPlaceholder)]) {
#ifdef __IPHONE_6_0
textField.attributedPlaceholder = [[NSAttributedString alloc]
initWithString:textField.placeholder attributes: // NOTE: textField.placeholder can't be nil
#{ NSForegroundColorAttributeName : placeholderColor,
NSFontAttributeName : placeholderFont }];
#endif
} else { // for pre-iOS6
[textField setValue:placeholderColor forKeyPath:#"_placeholderLabel.textColor"];
[textField setValue:placeholderFont forKeyPath:#"_placeholderLabel.font"];
}
You can use below code
First find name of system accepted font for your Custom font
for (NSString *familyName in [UIFont familyNames]) {
for (NSString *fontName in [UIFont fontNamesForFamilyName:familyName]) {
NSLog(#"%#", fontName);
}
}
and then use below code make your placeholder with custom font
searchTextField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:#"Where are you shopping?" attributes:#{NSFontAttributeName : font }];
Else there can be chance to get nil object[1] for font not found
let attributes: [NSAttributedStringKey : Any] = [NSAttributedStringKey.foregroundColor: UIColor.black,
NSAttributedStringKey.font: UIFont(name: "Menlo", size: 17.0) ?? UIFont.systemFont(ofSize: 17.0) ]
textField.attributedPlaceholder = NSAttributedString(string: "Placeholder Text", attributes: attributes)
Note: when we use UIFont(name: "Menlo", size: 17.0) method, if the font name can't get it in ios , so it will be nil, so we need to provide the default font. It was explained above.
You can use below code First find name of system accepted font for your Custom font
for (NSString *familyName in [UIFont familyNames]) {
for (NSString *fontName in [UIFont fontNamesForFamilyName:familyName]) {
NSLog(#"%#", fontName);
}
}
Swift 4: Placeholder Color change using UITextField subclass
override func drawPlaceholder(in rect: CGRect) {
let color = UIColor(red: 210/255, green: 210/255, blue: 210/255, alpha: 1.0)
if (placeholder?.responds(to: #selector(NSString.draw(in:withAttributes:))))! {
let fontS = UIFont.systemFont(ofSize: 12)
let attributes = [NSAttributedStringKey.foregroundColor: color, NSAttributedStringKey.font: fontS] as [NSAttributedStringKey : Any]
let boundingRect: CGRect = placeholder!.boundingRect(with: rect.size, options: [], attributes: attributes, context: nil)
placeholder?.draw(at: CGPoint(x: 0, y: (rect.size.height / 2) - boundingRect.size.height / 2), withAttributes: attributes)
}
}
if you have problem same me. I solve by set Font because some time font can't change when set Font in stroryboard or set in self.emailTextField.placeholder .
self.emailTextField.font = UIFont(..custom you font....)
You can change the font size of the text and placeholder by simply doing this.
field.font = .systemFont(ofSize: 16)

Resources