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!])
}
}
}
How do I change the placeholder text color of a UITextField through Swift? I can’t seem to access the placeholder attribute. Thanks
asked Dec 29, 2014 at 4:25
0
You can set the placeholder text using an Attributed string. Set color to attributes
Property.
textField.attributedPlaceholder = NSAttributedString(string:"placeholder text",
attributes:[NSForegroundColorAttributeName: UIColor.yellowColor()])
Swift 5
textField.attributedPlaceholder = NSAttributedString(string:"placeholder text", attributes:[NSAttributedString.Key.foregroundColor: UIColor.yellow])
answered Dec 29, 2014 at 4:29
iBhaviniBhavin
1,26115 silver badges30 bronze badges
Click on the + button and add a new runtime attribute: _placeholderLabel.textColor
Run your app.
answered Oct 7, 2015 at 7:31
Shashi VermaShashi Verma
3,7203 gold badges12 silver badges19 bronze badges
0
In swift you can change the placeholderColor by using the code,
name_textField .setValue(UIColor.redColor(), forKeyPath: "_placeholderLabel.textColor")
answered Dec 29, 2014 at 4:34
Vineesh TPVineesh TP
7,53912 gold badges63 silver badges125 bronze badges
5
You can create Subclass of Textfield and can override DrawRect function of textfield.
By creating subclass you can set that for every textfields Easily.
class CustomTextfield :UITextField {
override func drawRect(rect: CGRect) {
self.attributedPlaceholder = NSAttributedString(string:self.placeholder != nil ? self.placeholder! : "", attributes:[NSForegroundColorAttributeName: UIColor.grayColor()])
} }
answered Jul 18, 2016 at 9:04
BhavikBhavik
2092 silver badges4 bronze badges
Swift 4:
emailTextField.attributedPlaceholder = NSAttributedString(string: "e-mail", attributes: [NSAttributedStringKey.foregroundColor : UIColor.white])
answered Feb 13, 2018 at 13:20
DaniDani
4,6002 gold badges30 silver badges48 bronze badges
swift 5
text.attributedPlaceholder = NSAttributedString(string: "your holder text", attributes: [NSAttributedString.Key.foregroundColor : textHolderColor])
answered Aug 10, 2019 at 18:15
In this tutorial you will learn how to change the color of a UITextField’s placeholder text. This is a straight forward task but if you are anything like me and you see NSAttributedString
you start looking for a different solution. We are going to be using NSAttributedString
in this tutorial, but it is very basic and easy for what we need to do.
Before we start, I am going to assume that you have a text field set up. If not, you will need a text field set up for this tutorial.
I have a text field outlet and I will be using the attributed string to change the color in the didSet
property observer. Update your text field outlet to look like this:
@IBOutlet weak var textField: UITextField! {
didSet {
let redPlaceholderText = NSAttributedString(string: "My Placeholder",
attributes: [NSAttributedString.Key.foregroundColor: UIColor.red])
textField.attributedPlaceholder = redPlaceholderText
}
}
As mentioned before, this is a very simple attributed string. All we have done is create a new variable and assigned a new instance of NSAttributedString
to it. The first argument of the attributed string is the string we want to display, and the second argument is for the attributes we want to use.
In the above example we are only using the .foregroundColor
attribute and setting it to UIColor.red
for simplicity. You could make this any color you want.
The last thing that we have done is used the attributedPlaceholder
property instead of the normal placeholder
property. This will allow us to assign an attributed string as the placeholder text.
If you do not have the text field as an outlet, you could create a function that will assign the attributed string to the text field as we have done in the code.
Conclusion
Using an attributed string is actually quite simple, even if it does seem daunting at first. There are quite a few options that an attributed string will allow you to customise, such as the font, stroke color, stroke width, kern etc.
If you want to see my full source code, you can find it here.
Since the introduction of attributed strings in UIViews in iOS 6, it’s possible to assign a color to the placeholder text like this:
if ([textField respondsToSelector:@selector(setAttributedPlaceholder:)]) {
UIColor *color = [UIColor blackColor];
textField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:placeholderText attributes:@{NSForegroundColorAttributeName: color}];
} else {
NSLog(@"Cannot set placeholder text's color, because deployment target is earlier than iOS 6.0");
// TODO: Add fall-back code to set placeholder color.
}
answered Dec 4, 2012 at 3:08
user1071136user1071136
15.6k3 gold badges41 silver badges61 bronze badges
16
Easy and pain-free, could be an easy alternative for some.
_placeholderLabel.textColor
Not suggested for production, Apple may reject your submission.
answered Feb 25, 2014 at 14:28
JackJack
3,6027 gold badges44 silver badges66 bronze badges
11
You can override drawPlaceholderInRect:(CGRect)rect
as such to manually render the placeholder text:
- (void) drawPlaceholderInRect:(CGRect)rect {
[[UIColor blueColor] setFill];
[[self placeholder] drawInRect:rect withFont:[UIFont systemFontOfSize:16]];
}
Kuldeep
4,4187 gold badges32 silver badges56 bronze badges
answered Aug 3, 2010 at 11:35
adamadam
22.3k20 gold badges87 silver badges119 bronze badges
9
This works in Swift <3.0:
myTextField.attributedPlaceholder =
NSAttributedString(string: "placeholder text", attributes: [NSForegroundColorAttributeName : UIColor.redColor()])
Tested in iOS 8.2 and iOS 8.3 beta 4.
Swift 3:
myTextfield.attributedPlaceholder =
NSAttributedString(string: "placeholder text", attributes: [NSForegroundColorAttributeName : UIColor.red])
Swift 4:
myTextfield.attributedPlaceholder =
NSAttributedString(string: "placeholder text", attributes: [NSAttributedStringKey.foregroundColor: UIColor.red])
Swift 4.2:
myTextfield.attributedPlaceholder =
NSAttributedString(string: "placeholder text", attributes: [NSAttributedString.Key.foregroundColor: UIColor.red])
ekscrypto
3,6891 gold badge24 silver badges36 bronze badges
answered Jan 6, 2015 at 11:50
TominoTomino
5,7696 gold badges37 silver badges50 bronze badges
1
You can Change the Placeholder textcolor to any color which you want by using the below code.
UIColor *color = [UIColor lightTextColor];
YOURTEXTFIELD.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"PlaceHolder Text" attributes:@{NSForegroundColorAttributeName: color}];
answered Nov 8, 2013 at 6:18
ManjuManju
4,1332 gold badges18 silver badges12 bronze badges
8
Maybe you want to try this way, but Apple might warn you about accessing private ivar:
[self.myTextField setValue:[UIColor darkGrayColor]
forKeyPath:@"_placeholderLabel.textColor"];
NOTE
This is not working on iOS 7 anymore, according to Martin Alléus.
answered Jan 4, 2010 at 7:53
digdogdigdog
4,1901 gold badge26 silver badges23 bronze badges
14
Swift 3.0 + Storyboard
In order to change placeholder color in storyboard, create an extension with next code. (feel free to update this code, if you think, it can be clearer and safer).
extension UITextField {
@IBInspectable var placeholderColor: UIColor {
get {
guard let currentAttributedPlaceholderColor = attributedPlaceholder?.attribute(NSForegroundColorAttributeName, at: 0, effectiveRange: nil) as? UIColor else { return UIColor.clear }
return currentAttributedPlaceholderColor
}
set {
guard let currentAttributedString = attributedPlaceholder else { return }
let attributes = [NSForegroundColorAttributeName : newValue]
attributedPlaceholder = NSAttributedString(string: currentAttributedString.string, attributes: attributes)
}
}
}
Swift 4 version
extension UITextField {
@IBInspectable var placeholderColor: UIColor {
get {
return attributedPlaceholder?.attribute(.foregroundColor, at: 0, effectiveRange: nil) as? UIColor ?? .clear
}
set {
guard let attributedPlaceholder = attributedPlaceholder else { return }
let attributes: [NSAttributedStringKey: UIColor] = [.foregroundColor: newValue]
self.attributedPlaceholder = NSAttributedString(string: attributedPlaceholder.string, attributes: attributes)
}
}
}
Swift 5 version
extension UITextField {
@IBInspectable var placeholderColor: UIColor {
get {
return attributedPlaceholder?.attribute(.foregroundColor, at: 0, effectiveRange: nil) as? UIColor ?? .clear
}
set {
guard let attributedPlaceholder = attributedPlaceholder else { return }
let attributes: [NSAttributedString.Key: UIColor] = [.foregroundColor: newValue]
self.attributedPlaceholder = NSAttributedString(string: attributedPlaceholder.string, attributes: attributes)
}
}
}
DZoki019
3832 silver badges13 bronze badges
answered May 21, 2017 at 12:05
Nike KovNike Kov
12.7k7 gold badges69 silver badges112 bronze badges
2
In Swift:
if let placeholder = yourTextField.placeholder {
yourTextField.attributedPlaceholder = NSAttributedString(string:placeholder,
attributes: [NSForegroundColorAttributeName: UIColor.blackColor()])
}
In Swift 4.0:
if let placeholder = yourTextField.placeholder {
yourTextField.attributedPlaceholder = NSAttributedString(string:placeholder,
attributes: [NSAttributedStringKey.foregroundColor: UIColor.black])
}
clemens
16.2k11 gold badges46 silver badges62 bronze badges
answered Dec 11, 2014 at 16:22
Beninho85Beninho85
3,22327 silver badges22 bronze badges
4
The following only with iOS6+ (as indicated in Alexander W’s comment):
UIColor *color = [UIColor grayColor];
nameText.attributedPlaceholder =
[[NSAttributedString alloc]
initWithString:@"Full Name"
attributes:@{NSForegroundColorAttributeName:color}];
Fattie
29.9k66 gold badges412 silver badges697 bronze badges
answered May 19, 2014 at 6:33
0
I had already faced this issue. In my case below code is correct.
Objective C
[textField setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];
For Swift 4.X
tf_mobile.setValue(UIColor.white, forKeyPath: "_placeholderLabel.textColor")
For iOS 13 Swift Code
tf_mobile.attributedPlaceholder = NSAttributedString(string:"PlaceHolder Text", attributes: [NSAttributedString.Key.foregroundColor: UIColor.red])
You can also use below code for iOS 13
let iVar = class_getInstanceVariable(UITextField.self, "_placeholderLabel")!
let placeholderLabel = object_getIvar(tf_mobile, iVar) as! UILabel
placeholderLabel.textColor = .red
Hope, this may help you.
answered Jun 20, 2015 at 13:20
AshuAshu
3,33537 silver badges34 bronze badges
6
With this we can change the color of textfield’s placeholder text in iOS
[self.userNameTxt setValue:[UIColor colorWithRed:41.0/255.0 green:91.0/255.0 blue:106.0/255.0 alpha:1.0] forKeyPath:@"_placeholderLabel.textColor"];
Yogi
3,5583 gold badges34 silver badges56 bronze badges
answered Feb 12, 2016 at 7:30
Uma MadhaviUma Madhavi
4,8215 gold badges38 silver badges73 bronze badges
2
in swift 3.X
textField.attributedPlaceholder = NSAttributedString(string: "placeholder text", attributes:[NSForegroundColorAttributeName: UIColor.black])
in swift 5
textField.attributedPlaceholder = NSAttributedString(string: "placeholder text", attributes: [NSAttributedString.Key.foregroundColor : UIColor.black])
Joshua Wolff
2,3641 gold badge24 silver badges42 bronze badges
answered Jan 1, 2018 at 6:25
MAhipal SinghMAhipal Singh
4,6951 gold badge43 silver badges56 bronze badges
Why don’t you just use UIAppearance
method:
[[UILabel appearanceWhenContainedIn:[UITextField class], nil] setTextColor:[UIColor whateverColorYouNeed]];
Matthias
3,5622 gold badges30 silver badges41 bronze badges
answered Dec 19, 2013 at 13:08
2
Also in your storyboard, without single line of code
answered Feb 5, 2016 at 10:00
Petr SyrovPetr Syrov
14.5k3 gold badges19 silver badges30 bronze badges
5
For iOS 6.0 +
[textfield setValue:your_color forKeyPath:@"_placeholderLabel.textColor"];
Hope it helps.
Note: Apple may reject (0.01% chances) your app as we are accessing private API. I am using this in all my projects since two years, but Apple didn’t ask for this.
answered Dec 30, 2014 at 6:48
Fahim ParkarFahim Parkar
30.5k43 gold badges159 silver badges276 bronze badges
1
Swift version. Probably it would help someone.
class TextField: UITextField {
override var placeholder: String? {
didSet {
let placeholderString = NSAttributedString(string: placeholder!, attributes: [NSForegroundColorAttributeName: UIColor.whiteColor()])
self.attributedPlaceholder = placeholderString
}
}
}
Machado
13.8k13 gold badges51 silver badges96 bronze badges
answered Aug 29, 2016 at 10:05
Max TymchiiMax Tymchii
7267 silver badges16 bronze badges
0
iOS 6 and later offers attributedPlaceholder
on UITextField
.
iOS 3.2 and later offers setAttributes:range:
on NSMutableAttributedString
.
You can do the following:
NSMutableAttributedString *ms = [[NSMutableAttributedString alloc] initWithString:self.yourInput.placeholder];
UIFont *placeholderFont = self.yourInput.font;
NSRange fullRange = NSMakeRange(0, ms.length);
NSDictionary *newProps = @{NSForegroundColorAttributeName:[UIColor yourColor], NSFontAttributeName:placeholderFont};
[ms setAttributes:newProps range:fullRange];
self.yourInput.attributedPlaceholder = ms;
Kuldeep
4,4187 gold badges32 silver badges56 bronze badges
answered Oct 2, 2013 at 1:21
2
To handle both vertical and horizontal alignment as well as color of placeholder in iOS7. drawInRect and drawAtPoint no longer use current context fillColor.
https://developer.apple.com/library/ios/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/CustomTextProcessing/CustomTextProcessing.html
Obj-C
@interface CustomPlaceHolderTextColorTextField : UITextField
@end
@implementation CustomPlaceHolderTextColorTextField : UITextField
-(void) drawPlaceholderInRect:(CGRect)rect {
if (self.placeholder) {
// color of placeholder text
UIColor *placeHolderTextColor = [UIColor redColor];
CGSize drawSize = [self.placeholder sizeWithAttributes:[NSDictionary dictionaryWithObject:self.font forKey:NSFontAttributeName]];
CGRect drawRect = rect;
// verticially align text
drawRect.origin.y = (rect.size.height - drawSize.height) * 0.5;
// set alignment
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.alignment = self.textAlignment;
// dictionary of attributes, font, paragraphstyle, and color
NSDictionary *drawAttributes = @{NSFontAttributeName: self.font,
NSParagraphStyleAttributeName : paragraphStyle,
NSForegroundColorAttributeName : placeHolderTextColor};
// draw
[self.placeholder drawInRect:drawRect withAttributes:drawAttributes];
}
}
@end
Kuldeep
4,4187 gold badges32 silver badges56 bronze badges
answered Nov 2, 2013 at 15:22
1
This solution for Swift 4.1
textName.attributedPlaceholder = NSAttributedString(string: textName.placeholder!, attributes: [NSAttributedStringKey.foregroundColor : UIColor.red])
answered Oct 10, 2018 at 9:54
Categories FTW. Could be optimized to check for effective color change.
#import <UIKit/UIKit.h>
@interface UITextField (OPConvenience)
@property (strong, nonatomic) UIColor* placeholderColor;
@end
#import "UITextField+OPConvenience.h"
@implementation UITextField (OPConvenience)
- (void) setPlaceholderColor: (UIColor*) color {
if (color) {
NSMutableAttributedString* attrString = [self.attributedPlaceholder mutableCopy];
[attrString setAttributes: @{NSForegroundColorAttributeName: color} range: NSMakeRange(0, attrString.length)];
self.attributedPlaceholder = attrString;
}
}
- (UIColor*) placeholderColor {
return [self.attributedPlaceholder attribute: NSForegroundColorAttributeName atIndex: 0 effectiveRange: NULL];
}
@end
answered May 27, 2014 at 20:35
osxdirkosxdirk
5606 silver badges11 bronze badges
0
Swift 5 WITH CAVEAT.
let attributes = [ NSAttributedString.Key.foregroundColor: UIColor.someColor ]
let placeHolderString = NSAttributedString(string: "DON'T_DELETE", attributes: attributes)
txtField.attributedPlaceholder = placeHolderString
The caveat being that you MUST enter a non-empty String
where «DON’T_DELETE» is, even if that string is set in code elsewhere. Might save you five minutes of head-sctratching.
-
if subclassing you MUST do it in layoutSubviews (not in init)
-
strangely you do NOT have to clear the normal
placeholder
. it knows to not drawplaceholder
if you’re using the attributed placeholder.
Fattie
29.9k66 gold badges412 silver badges697 bronze badges
answered Oct 31, 2019 at 2:00
HenryRootTwoHenryRootTwo
2,5421 gold badge27 silver badges27 bronze badges
Overriding drawPlaceholderInRect:
would be the correct way, but it does not work due to a bug in the API (or the documentation).
The method never gets called on an UITextField
.
See also drawTextInRect on UITextField not called
You might use digdog’s solution. As I am not sure if that gets past Apples review, I chose a different solution: Overlay the text field with my own label which imitates the placeholder behaviour.
This is a bit messy though.
The code looks like this (Note I am doing this inside a subclass of TextField):
@implementation PlaceholderChangingTextField
- (void) changePlaceholderColor:(UIColor*)color
{
// Need to place the overlay placeholder exactly above the original placeholder
UILabel *overlayPlaceholderLabel = [[[UILabel alloc] initWithFrame:CGRectMake(self.frame.origin.x + 8, self.frame.origin.y + 4, self.frame.size.width - 16, self.frame.size.height - 8)] autorelease];
overlayPlaceholderLabel.backgroundColor = [UIColor whiteColor];
overlayPlaceholderLabel.opaque = YES;
overlayPlaceholderLabel.text = self.placeholder;
overlayPlaceholderLabel.textColor = color;
overlayPlaceholderLabel.font = self.font;
// Need to add it to the superview, as otherwise we cannot overlay the buildin text label.
[self.superview addSubview:overlayPlaceholderLabel];
self.placeholder = nil;
}
answered Apr 6, 2010 at 0:03
henning77henning77
3,8042 gold badges26 silver badges32 bronze badges
3
Iam new to xcode and i found a way around to the same effect.
I placed a uilabel in place of place holder with the desired format and hide it in
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
switch (textField.tag)
{
case 0:
lblUserName.hidden=YES;
break;
case 1:
lblPassword.hidden=YES;
break;
default:
break;
}
}
I agree its a work around and not a real solution but the effect was same got it from this link
NOTE: Still works on iOS 7
answered May 23, 2012 at 9:14
amaramar
4,2757 gold badges40 silver badges51 bronze badges
The best i can do for both iOS7 and less is:
- (CGRect)placeholderRectForBounds:(CGRect)bounds {
return [self textRectForBounds:bounds];
}
- (CGRect)editingRectForBounds:(CGRect)bounds {
return [self textRectForBounds:bounds];
}
- (CGRect)textRectForBounds:(CGRect)bounds {
CGRect rect = CGRectInset(bounds, 0, 6); //TODO: can be improved by comparing font size versus bounds.size.height
return rect;
}
- (void)drawPlaceholderInRect:(CGRect)rect {
UIColor *color =RGBColor(65, 65, 65);
if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"7.0")) {
[self.placeholder drawInRect:rect withAttributes:@{NSFontAttributeName:self.font, UITextAttributeTextColor:color}];
} else {
[color setFill];
[self.placeholder drawInRect:rect withFont:self.font];
}
}
answered Sep 25, 2013 at 7:02
For those using Monotouch (Xamarin.iOS), here’s Adam’s answer, translated to C#:
public class MyTextBox : UITextField
{
public override void DrawPlaceholder(RectangleF rect)
{
UIColor.FromWhiteAlpha(0.5f, 1f).SetFill();
new NSString(this.Placeholder).DrawString(rect, Font);
}
}
answered Sep 18, 2013 at 17:15
DiegoDiego
17.8k5 gold badges61 silver badges66 bronze badges
1
For set Attributed Textfield Placeholder with Multiple color ,
Just specify the Text ,
//txtServiceText is your Textfield
_txtServiceText.placeholder=@"Badal/ Shah";
NSMutableAttributedString *mutable = [[NSMutableAttributedString alloc] initWithString:_txtServiceText.placeholder];
[mutable addAttribute: NSForegroundColorAttributeName value:[UIColor whiteColor] range:[_txtServiceText.placeholder rangeOfString:@"Badal/"]]; //Replace it with your first color Text
[mutable addAttribute: NSForegroundColorAttributeName value:[UIColor orangeColor] range:[_txtServiceText.placeholder rangeOfString:@"Shah"]]; // Replace it with your secondcolor string.
_txtServiceText.attributedPlaceholder=mutable;
Output :-
answered May 20, 2016 at 5:52
Badal ShahBadal Shah
7,5212 gold badges28 silver badges65 bronze badges
I needed to keep the placeholder alignment so adam’s answer was not enough for me.
To solve this I used a small variation that I hope will help some of you too:
- (void) drawPlaceholderInRect:(CGRect)rect {
//search field placeholder color
UIColor* color = [UIColor whiteColor];
[color setFill];
[self.placeholder drawInRect:rect withFont:self.font lineBreakMode:UILineBreakModeTailTruncation alignment:self.textAlignment];
}
answered Jun 10, 2013 at 10:13
Tomer EvenTomer Even
4,7762 gold badges29 silver badges36 bronze badges
1
[txt_field setValue:ColorFromHEX(@"#525252") forKeyPath:@"_placeholderLabel.textColor"];
MaxEcho
14.2k6 gold badges80 silver badges88 bronze badges
answered Apr 23, 2014 at 9:34
1
Another option that doesn’t require subclassing — leave placeholder blank, and put a label on top of edit button. Manage the label just like you would manage the placeholder (clearing once user inputs anything..)
answered Dec 6, 2010 at 22:34
kolinkokolinko
1,6331 gold badge14 silver badges31 bronze badges
1
Since the introduction of attributed strings in UIViews in iOS 6, it’s possible to assign a color to the placeholder text like this:
if ([textField respondsToSelector:@selector(setAttributedPlaceholder:)]) {
UIColor *color = [UIColor blackColor];
textField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:placeholderText attributes:@{NSForegroundColorAttributeName: color}];
} else {
NSLog(@"Cannot set placeholder text's color, because deployment target is earlier than iOS 6.0");
// TODO: Add fall-back code to set placeholder color.
}
answered Dec 4, 2012 at 3:08
user1071136user1071136
15.6k3 gold badges41 silver badges61 bronze badges
16
Easy and pain-free, could be an easy alternative for some.
_placeholderLabel.textColor
Not suggested for production, Apple may reject your submission.
answered Feb 25, 2014 at 14:28
JackJack
3,6027 gold badges44 silver badges66 bronze badges
11
You can override drawPlaceholderInRect:(CGRect)rect
as such to manually render the placeholder text:
- (void) drawPlaceholderInRect:(CGRect)rect {
[[UIColor blueColor] setFill];
[[self placeholder] drawInRect:rect withFont:[UIFont systemFontOfSize:16]];
}
Kuldeep
4,4187 gold badges32 silver badges56 bronze badges
answered Aug 3, 2010 at 11:35
adamadam
22.3k20 gold badges87 silver badges119 bronze badges
9
This works in Swift <3.0:
myTextField.attributedPlaceholder =
NSAttributedString(string: "placeholder text", attributes: [NSForegroundColorAttributeName : UIColor.redColor()])
Tested in iOS 8.2 and iOS 8.3 beta 4.
Swift 3:
myTextfield.attributedPlaceholder =
NSAttributedString(string: "placeholder text", attributes: [NSForegroundColorAttributeName : UIColor.red])
Swift 4:
myTextfield.attributedPlaceholder =
NSAttributedString(string: "placeholder text", attributes: [NSAttributedStringKey.foregroundColor: UIColor.red])
Swift 4.2:
myTextfield.attributedPlaceholder =
NSAttributedString(string: "placeholder text", attributes: [NSAttributedString.Key.foregroundColor: UIColor.red])
ekscrypto
3,6891 gold badge24 silver badges36 bronze badges
answered Jan 6, 2015 at 11:50
TominoTomino
5,7696 gold badges37 silver badges50 bronze badges
1
You can Change the Placeholder textcolor to any color which you want by using the below code.
UIColor *color = [UIColor lightTextColor];
YOURTEXTFIELD.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"PlaceHolder Text" attributes:@{NSForegroundColorAttributeName: color}];
answered Nov 8, 2013 at 6:18
ManjuManju
4,1332 gold badges18 silver badges12 bronze badges
8
Maybe you want to try this way, but Apple might warn you about accessing private ivar:
[self.myTextField setValue:[UIColor darkGrayColor]
forKeyPath:@"_placeholderLabel.textColor"];
NOTE
This is not working on iOS 7 anymore, according to Martin Alléus.
answered Jan 4, 2010 at 7:53
digdogdigdog
4,1901 gold badge26 silver badges23 bronze badges
14
Swift 3.0 + Storyboard
In order to change placeholder color in storyboard, create an extension with next code. (feel free to update this code, if you think, it can be clearer and safer).
extension UITextField {
@IBInspectable var placeholderColor: UIColor {
get {
guard let currentAttributedPlaceholderColor = attributedPlaceholder?.attribute(NSForegroundColorAttributeName, at: 0, effectiveRange: nil) as? UIColor else { return UIColor.clear }
return currentAttributedPlaceholderColor
}
set {
guard let currentAttributedString = attributedPlaceholder else { return }
let attributes = [NSForegroundColorAttributeName : newValue]
attributedPlaceholder = NSAttributedString(string: currentAttributedString.string, attributes: attributes)
}
}
}
Swift 4 version
extension UITextField {
@IBInspectable var placeholderColor: UIColor {
get {
return attributedPlaceholder?.attribute(.foregroundColor, at: 0, effectiveRange: nil) as? UIColor ?? .clear
}
set {
guard let attributedPlaceholder = attributedPlaceholder else { return }
let attributes: [NSAttributedStringKey: UIColor] = [.foregroundColor: newValue]
self.attributedPlaceholder = NSAttributedString(string: attributedPlaceholder.string, attributes: attributes)
}
}
}
Swift 5 version
extension UITextField {
@IBInspectable var placeholderColor: UIColor {
get {
return attributedPlaceholder?.attribute(.foregroundColor, at: 0, effectiveRange: nil) as? UIColor ?? .clear
}
set {
guard let attributedPlaceholder = attributedPlaceholder else { return }
let attributes: [NSAttributedString.Key: UIColor] = [.foregroundColor: newValue]
self.attributedPlaceholder = NSAttributedString(string: attributedPlaceholder.string, attributes: attributes)
}
}
}
DZoki019
3832 silver badges13 bronze badges
answered May 21, 2017 at 12:05
Nike KovNike Kov
12.7k7 gold badges69 silver badges112 bronze badges
2
In Swift:
if let placeholder = yourTextField.placeholder {
yourTextField.attributedPlaceholder = NSAttributedString(string:placeholder,
attributes: [NSForegroundColorAttributeName: UIColor.blackColor()])
}
In Swift 4.0:
if let placeholder = yourTextField.placeholder {
yourTextField.attributedPlaceholder = NSAttributedString(string:placeholder,
attributes: [NSAttributedStringKey.foregroundColor: UIColor.black])
}
clemens
16.2k11 gold badges46 silver badges62 bronze badges
answered Dec 11, 2014 at 16:22
Beninho85Beninho85
3,22327 silver badges22 bronze badges
4
The following only with iOS6+ (as indicated in Alexander W’s comment):
UIColor *color = [UIColor grayColor];
nameText.attributedPlaceholder =
[[NSAttributedString alloc]
initWithString:@"Full Name"
attributes:@{NSForegroundColorAttributeName:color}];
Fattie
29.9k66 gold badges412 silver badges697 bronze badges
answered May 19, 2014 at 6:33
0
I had already faced this issue. In my case below code is correct.
Objective C
[textField setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];
For Swift 4.X
tf_mobile.setValue(UIColor.white, forKeyPath: "_placeholderLabel.textColor")
For iOS 13 Swift Code
tf_mobile.attributedPlaceholder = NSAttributedString(string:"PlaceHolder Text", attributes: [NSAttributedString.Key.foregroundColor: UIColor.red])
You can also use below code for iOS 13
let iVar = class_getInstanceVariable(UITextField.self, "_placeholderLabel")!
let placeholderLabel = object_getIvar(tf_mobile, iVar) as! UILabel
placeholderLabel.textColor = .red
Hope, this may help you.
answered Jun 20, 2015 at 13:20
AshuAshu
3,33537 silver badges34 bronze badges
6
With this we can change the color of textfield’s placeholder text in iOS
[self.userNameTxt setValue:[UIColor colorWithRed:41.0/255.0 green:91.0/255.0 blue:106.0/255.0 alpha:1.0] forKeyPath:@"_placeholderLabel.textColor"];
Yogi
3,5583 gold badges34 silver badges56 bronze badges
answered Feb 12, 2016 at 7:30
Uma MadhaviUma Madhavi
4,8215 gold badges38 silver badges73 bronze badges
2
in swift 3.X
textField.attributedPlaceholder = NSAttributedString(string: "placeholder text", attributes:[NSForegroundColorAttributeName: UIColor.black])
in swift 5
textField.attributedPlaceholder = NSAttributedString(string: "placeholder text", attributes: [NSAttributedString.Key.foregroundColor : UIColor.black])
Joshua Wolff
2,3641 gold badge24 silver badges42 bronze badges
answered Jan 1, 2018 at 6:25
MAhipal SinghMAhipal Singh
4,6951 gold badge43 silver badges56 bronze badges
Why don’t you just use UIAppearance
method:
[[UILabel appearanceWhenContainedIn:[UITextField class], nil] setTextColor:[UIColor whateverColorYouNeed]];
Matthias
3,5622 gold badges30 silver badges41 bronze badges
answered Dec 19, 2013 at 13:08
2
Also in your storyboard, without single line of code
answered Feb 5, 2016 at 10:00
Petr SyrovPetr Syrov
14.5k3 gold badges19 silver badges30 bronze badges
5
For iOS 6.0 +
[textfield setValue:your_color forKeyPath:@"_placeholderLabel.textColor"];
Hope it helps.
Note: Apple may reject (0.01% chances) your app as we are accessing private API. I am using this in all my projects since two years, but Apple didn’t ask for this.
answered Dec 30, 2014 at 6:48
Fahim ParkarFahim Parkar
30.5k43 gold badges159 silver badges276 bronze badges
1
Swift version. Probably it would help someone.
class TextField: UITextField {
override var placeholder: String? {
didSet {
let placeholderString = NSAttributedString(string: placeholder!, attributes: [NSForegroundColorAttributeName: UIColor.whiteColor()])
self.attributedPlaceholder = placeholderString
}
}
}
Machado
13.8k13 gold badges51 silver badges96 bronze badges
answered Aug 29, 2016 at 10:05
Max TymchiiMax Tymchii
7267 silver badges16 bronze badges
0
iOS 6 and later offers attributedPlaceholder
on UITextField
.
iOS 3.2 and later offers setAttributes:range:
on NSMutableAttributedString
.
You can do the following:
NSMutableAttributedString *ms = [[NSMutableAttributedString alloc] initWithString:self.yourInput.placeholder];
UIFont *placeholderFont = self.yourInput.font;
NSRange fullRange = NSMakeRange(0, ms.length);
NSDictionary *newProps = @{NSForegroundColorAttributeName:[UIColor yourColor], NSFontAttributeName:placeholderFont};
[ms setAttributes:newProps range:fullRange];
self.yourInput.attributedPlaceholder = ms;
Kuldeep
4,4187 gold badges32 silver badges56 bronze badges
answered Oct 2, 2013 at 1:21
2
To handle both vertical and horizontal alignment as well as color of placeholder in iOS7. drawInRect and drawAtPoint no longer use current context fillColor.
https://developer.apple.com/library/ios/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/CustomTextProcessing/CustomTextProcessing.html
Obj-C
@interface CustomPlaceHolderTextColorTextField : UITextField
@end
@implementation CustomPlaceHolderTextColorTextField : UITextField
-(void) drawPlaceholderInRect:(CGRect)rect {
if (self.placeholder) {
// color of placeholder text
UIColor *placeHolderTextColor = [UIColor redColor];
CGSize drawSize = [self.placeholder sizeWithAttributes:[NSDictionary dictionaryWithObject:self.font forKey:NSFontAttributeName]];
CGRect drawRect = rect;
// verticially align text
drawRect.origin.y = (rect.size.height - drawSize.height) * 0.5;
// set alignment
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.alignment = self.textAlignment;
// dictionary of attributes, font, paragraphstyle, and color
NSDictionary *drawAttributes = @{NSFontAttributeName: self.font,
NSParagraphStyleAttributeName : paragraphStyle,
NSForegroundColorAttributeName : placeHolderTextColor};
// draw
[self.placeholder drawInRect:drawRect withAttributes:drawAttributes];
}
}
@end
Kuldeep
4,4187 gold badges32 silver badges56 bronze badges
answered Nov 2, 2013 at 15:22
1
This solution for Swift 4.1
textName.attributedPlaceholder = NSAttributedString(string: textName.placeholder!, attributes: [NSAttributedStringKey.foregroundColor : UIColor.red])
answered Oct 10, 2018 at 9:54
Categories FTW. Could be optimized to check for effective color change.
#import <UIKit/UIKit.h>
@interface UITextField (OPConvenience)
@property (strong, nonatomic) UIColor* placeholderColor;
@end
#import "UITextField+OPConvenience.h"
@implementation UITextField (OPConvenience)
- (void) setPlaceholderColor: (UIColor*) color {
if (color) {
NSMutableAttributedString* attrString = [self.attributedPlaceholder mutableCopy];
[attrString setAttributes: @{NSForegroundColorAttributeName: color} range: NSMakeRange(0, attrString.length)];
self.attributedPlaceholder = attrString;
}
}
- (UIColor*) placeholderColor {
return [self.attributedPlaceholder attribute: NSForegroundColorAttributeName atIndex: 0 effectiveRange: NULL];
}
@end
answered May 27, 2014 at 20:35
osxdirkosxdirk
5606 silver badges11 bronze badges
0
Swift 5 WITH CAVEAT.
let attributes = [ NSAttributedString.Key.foregroundColor: UIColor.someColor ]
let placeHolderString = NSAttributedString(string: "DON'T_DELETE", attributes: attributes)
txtField.attributedPlaceholder = placeHolderString
The caveat being that you MUST enter a non-empty String
where «DON’T_DELETE» is, even if that string is set in code elsewhere. Might save you five minutes of head-sctratching.
-
if subclassing you MUST do it in layoutSubviews (not in init)
-
strangely you do NOT have to clear the normal
placeholder
. it knows to not drawplaceholder
if you’re using the attributed placeholder.
Fattie
29.9k66 gold badges412 silver badges697 bronze badges
answered Oct 31, 2019 at 2:00
HenryRootTwoHenryRootTwo
2,5421 gold badge27 silver badges27 bronze badges
Overriding drawPlaceholderInRect:
would be the correct way, but it does not work due to a bug in the API (or the documentation).
The method never gets called on an UITextField
.
See also drawTextInRect on UITextField not called
You might use digdog’s solution. As I am not sure if that gets past Apples review, I chose a different solution: Overlay the text field with my own label which imitates the placeholder behaviour.
This is a bit messy though.
The code looks like this (Note I am doing this inside a subclass of TextField):
@implementation PlaceholderChangingTextField
- (void) changePlaceholderColor:(UIColor*)color
{
// Need to place the overlay placeholder exactly above the original placeholder
UILabel *overlayPlaceholderLabel = [[[UILabel alloc] initWithFrame:CGRectMake(self.frame.origin.x + 8, self.frame.origin.y + 4, self.frame.size.width - 16, self.frame.size.height - 8)] autorelease];
overlayPlaceholderLabel.backgroundColor = [UIColor whiteColor];
overlayPlaceholderLabel.opaque = YES;
overlayPlaceholderLabel.text = self.placeholder;
overlayPlaceholderLabel.textColor = color;
overlayPlaceholderLabel.font = self.font;
// Need to add it to the superview, as otherwise we cannot overlay the buildin text label.
[self.superview addSubview:overlayPlaceholderLabel];
self.placeholder = nil;
}
answered Apr 6, 2010 at 0:03
henning77henning77
3,8042 gold badges26 silver badges32 bronze badges
3
Iam new to xcode and i found a way around to the same effect.
I placed a uilabel in place of place holder with the desired format and hide it in
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
switch (textField.tag)
{
case 0:
lblUserName.hidden=YES;
break;
case 1:
lblPassword.hidden=YES;
break;
default:
break;
}
}
I agree its a work around and not a real solution but the effect was same got it from this link
NOTE: Still works on iOS 7
answered May 23, 2012 at 9:14
amaramar
4,2757 gold badges40 silver badges51 bronze badges
The best i can do for both iOS7 and less is:
- (CGRect)placeholderRectForBounds:(CGRect)bounds {
return [self textRectForBounds:bounds];
}
- (CGRect)editingRectForBounds:(CGRect)bounds {
return [self textRectForBounds:bounds];
}
- (CGRect)textRectForBounds:(CGRect)bounds {
CGRect rect = CGRectInset(bounds, 0, 6); //TODO: can be improved by comparing font size versus bounds.size.height
return rect;
}
- (void)drawPlaceholderInRect:(CGRect)rect {
UIColor *color =RGBColor(65, 65, 65);
if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"7.0")) {
[self.placeholder drawInRect:rect withAttributes:@{NSFontAttributeName:self.font, UITextAttributeTextColor:color}];
} else {
[color setFill];
[self.placeholder drawInRect:rect withFont:self.font];
}
}
answered Sep 25, 2013 at 7:02
For those using Monotouch (Xamarin.iOS), here’s Adam’s answer, translated to C#:
public class MyTextBox : UITextField
{
public override void DrawPlaceholder(RectangleF rect)
{
UIColor.FromWhiteAlpha(0.5f, 1f).SetFill();
new NSString(this.Placeholder).DrawString(rect, Font);
}
}
answered Sep 18, 2013 at 17:15
DiegoDiego
17.8k5 gold badges61 silver badges66 bronze badges
1
For set Attributed Textfield Placeholder with Multiple color ,
Just specify the Text ,
//txtServiceText is your Textfield
_txtServiceText.placeholder=@"Badal/ Shah";
NSMutableAttributedString *mutable = [[NSMutableAttributedString alloc] initWithString:_txtServiceText.placeholder];
[mutable addAttribute: NSForegroundColorAttributeName value:[UIColor whiteColor] range:[_txtServiceText.placeholder rangeOfString:@"Badal/"]]; //Replace it with your first color Text
[mutable addAttribute: NSForegroundColorAttributeName value:[UIColor orangeColor] range:[_txtServiceText.placeholder rangeOfString:@"Shah"]]; // Replace it with your secondcolor string.
_txtServiceText.attributedPlaceholder=mutable;
Output :-
answered May 20, 2016 at 5:52
Badal ShahBadal Shah
7,5212 gold badges28 silver badges65 bronze badges
I needed to keep the placeholder alignment so adam’s answer was not enough for me.
To solve this I used a small variation that I hope will help some of you too:
- (void) drawPlaceholderInRect:(CGRect)rect {
//search field placeholder color
UIColor* color = [UIColor whiteColor];
[color setFill];
[self.placeholder drawInRect:rect withFont:self.font lineBreakMode:UILineBreakModeTailTruncation alignment:self.textAlignment];
}
answered Jun 10, 2013 at 10:13
Tomer EvenTomer Even
4,7762 gold badges29 silver badges36 bronze badges
1
[txt_field setValue:ColorFromHEX(@"#525252") forKeyPath:@"_placeholderLabel.textColor"];
MaxEcho
14.2k6 gold badges80 silver badges88 bronze badges
answered Apr 23, 2014 at 9:34
1
Another option that doesn’t require subclassing — leave placeholder blank, and put a label on top of edit button. Manage the label just like you would manage the placeholder (clearing once user inputs anything..)
answered Dec 6, 2010 at 22:34
kolinkokolinko
1,6331 gold badge14 silver badges31 bronze badges
1
24 ответа
Вы можете установить заполнитель текста, используя приписанную строку. Передайте цвет, который вы хотите с attributes
:
var myTextField = UITextField(frame: CGRect(x: 0, y: 0, width: 200, height: 30))
myTextField.backgroundColor = .blue
myTextField.attributedPlaceholder = NSAttributedString(string: "placeholder text",
attributes: [NSForegroundColorAttributeName: UIColor.yellow])
Для Swift 3+ используйте следующее:
myTextField.attributedPlaceholder = NSAttributedString(string: "placeholder text",
attributes: [NSAttributedStringKey.foregroundColor: UIColor.white])
Для Swift 4.2 используйте следующее:
myTextField.attributedPlaceholder = NSAttributedString(string: "placeholder text",
attributes: [NSAttributedString.Key.foregroundColor: UIColor.white])
vacawama
27 сен. 2014, в 16:22
Поделиться
Вы можете сделать это быстро, без добавления строки кода, используя Interface Builder.
Выберите UITextField
и откройте инспектор удостоверений справа:
Нажмите кнопку «плюс» и добавьте новый атрибут времени выполнения:
placeholderLabel.textColor (Swift 4)
_placeholderLabel.textColor (Swift 3 или меньше)
Используйте Цвет как тип и выберите цвет.
Это!
Вы не увидите результат, пока не запустите приложение снова.
crubio
27 авг. 2015, в 09:26
Поделиться
Создайте расширение UITextField
следующим образом:
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!])
}
}
}
И в вашей раскадровке или.xib. Ты увидишь
jose920405
24 май 2016, в 16:42
Поделиться
Этот код работает в Swift3:
yourTextFieldName .setValue(UIColor.init(colorLiteralRed: 80/255, green: 80/255, blue: 80/255, alpha: 1.0), forKeyPath: "_placeholderLabel.textColor")
сообщите мне, есть ли у вас проблемы.
Tejinder
27 сен. 2016, в 05:59
Поделиться
В Swift 3.0 используйте
let color = UIColor.lightText
textField.attributedPlaceholder = NSAttributedString(string: textField.placeholder, attributes: [NSForegroundColorAttributeName : color])
Sreedeepkesav M S
10 фев. 2017, в 18:17
Поделиться
Чтобы установить цвет заполнителя один раз для всех UITextField
в вашем приложении, вы можете сделать следующее:
UILabel.appearanceWhenContainedInInstancesOfClasses([UITextField.self]).textColor = UIColor.redColor()
Это позволит установить желаемый цвет для всех заполнителей TextField
во всем приложении. Но это доступно только с iOS 9.
До появления iOS 9 в swift нет метода appearenceWhenContainedIn….(), но вы можете использовать одно из представленных здесь решений.
Krzynool
17 фев. 2016, в 15:55
Поделиться
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!])
}
}
}
Khawar Islam
21 фев. 2018, в 16:07
Поделиться
Для Swift 4.0, X-code версии 9.1 или iOS 11 вы можете использовать следующий синтаксис, чтобы иметь другой цвет-заполнитель
textField.attributedPlaceholder = NSAttributedString(string: "Placeholder Text", attributes: [NSAttributedStringKey.foregroundColor : UIColor.white])
Ashim Dahal
05 нояб. 2017, в 05:15
Поделиться
Для Swift 3 и 3.1 это отлично работает:
passField.attributedPlaceholder = NSAttributedString(string: "password", attributes: [NSForegroundColorAttributeName: UIColor.white])
Asfand Shabbir
13 окт. 2017, в 08:10
Поделиться
В Swift 3 (возможно, 2) вы можете переопределить didSet для заполнителя в подклассе UITextField
чтобы применить к нему атрибут следующим образом:
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
}
}
ninja_iOS
10 янв. 2017, в 15:26
Поделиться
Вот моя быстрая реализация 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])
}
}
использовать как:
streetTextField?.placeholderColor(AppColor.blueColor)
надеюсь, это поможет кому-то!
Paul Lehn
09 фев. 2018, в 21:04
Поделиться
Для Свифта
Создать расширение UITextField
extension UITextField{
func setPlaceHolderColor(){
self.attributedPlaceholder = NSAttributedString(string: self.placeholder!, attributes: [NSForegroundColorAttributeName : UIColor.white])
}
}
Если вы установлены из раскадровки.
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!])
}
}
}
Dixit Akabari
21 июль 2017, в 08:21
Поделиться
В моем случае я сделал следующее:
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])
}
}
}
}
Pradip Patel
25 дек. 2018, в 06:42
Поделиться
Я удивлен, увидев, сколько здесь плохих решений.
Вот версия, которая всегда будет работать.
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])
}
}
}
СОВЕТ: Если вы измените текст заполнителя после установки color-, цвет будет сброшен.
David Rees
12 дек. 2018, в 03:42
Поделиться
Здесь я пишу все UIDesignable из UITextField. С помощью этого кода вы можете напрямую получить к нему доступ из UI файла инспектора в раскадровке
@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!])
}
}
}
Vikas Rajput
31 янв. 2019, в 07:05
Поделиться
Свифт 4:
txtControl.attributedPlaceholder = NSAttributedString(string: "Placeholder String...",attributes: [NSAttributedStringKey.foregroundColor: UIColor.gray])
Álvaro Agüero
31 дек. 2018, в 21:09
Поделиться
Для Swift 4.2 и выше вы можете сделать это, как показано ниже:
textField.attributedPlaceholder = NSAttributedString(string: "Placeholder Text", attributes: [NSAttributedString.Key.foregroundColor: UIColor.white])
Anindya
09 окт. 2018, в 11:30
Поделиться
Обновление ответа Crubio для Swift 4
Выберите UITextField и откройте инспектор удостоверений справа:
Нажмите кнопку «плюс» и добавьте новый атрибут времени выполнения: placeholderLabel.textColor (вместо _placeholderLabel.textColor)
Используйте Цвет как тип и выберите цвет.
Если вы запустите свой проект, вы увидите изменения.
Dris
13 июль 2018, в 22:02
Поделиться
Это больше о персонализации вашего textField, но в любом случае я поделюсь этим кодом, полученным с другой страницы, и сделал его немного лучше:
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]
)
}
}
И вы можете использовать это так:
self.textField.setBottomLine(borderColor: lineColor, fontColor: fontColor, placeHolderColor: placeHolderColor, placeHolder: placeHolder)
Зная, что у вас есть UITextField
подключенный к ViewController
.
Источник: http://codepany.com/blog/swift-3-custom-uitextfield-with-single-line-input/
LagMaster
31 окт. 2017, в 21:08
Поделиться
Для Swift
func setPlaceholderColor(textField: UITextField, placeholderText: String) {
textField.attributedPlaceholder = NSAttributedString(string: placeholderText, attributes: [NSForegroundColorAttributeName: UIColor.pelorBlack])
}
Вы можете использовать это:
self.setPlaceholderColor(textField: self.emailTextField, placeholderText: "E-Mail/Username")
Celil Bozkurt
09 июль 2017, в 19:54
Поделиться
Для чего я решил это, добавив метку поверх ввода и добавив равную ширину, равную высоту и средние ограничения X/Y.
Затем я использовал протокол делегата UITextField
, чтобы скрыть/показать эту метку, когда длина текста больше 0 или 0 соответственно. Это может быть выполнено с помощью Editing Changed
IBAction из текстового поля.
Это добавляет преимущества гораздо большего количества настроек для вашего заполнителя, чем просто цвет текста. Это также означает, что курсор не будет компенсирован текстом-заполнителем, а затем переместится в начало строки при вводе первого символа, который я сам нахожу раздражающим.
nickdnk
14 фев. 2017, в 19:05
Поделиться
yourTextfield.attributedPlaceholder = NSAttributedString(string: "your placeholder text",attributes: [NSForegroundColorAttributeName: UIColor.white])
Durga Ballabha Panigrahi
10 фев. 2017, в 12:44
Поделиться
Для Swift 4
txtField1.attributedPlaceholder = NSAttributedString(string: "-", attributes: [NSAttributedStringKey.foregroundColor: UIColor.white])
Arjun Dobaria
06 март 2018, в 09:13
Поделиться
Используйте это для добавления атрибутного заполнителя:
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)
Codewithj
29 июль 2017, в 09:30
Поделиться
Ещё вопросы
- 1Просмотр миниатюр в Android
- 0Как запретить просмотр кода сайта
- 0горизонтальное подменю css не работает
- 1Перекрасить JPanel при нажатии клавиши. (Ява)
- 1ViewModel для макета
- 0HTML — Как я могу контролировать размещение элементов
- 0Не удается найти правильный синтаксис массива JSON для Highcharts
- 0Генерация файлов из XML для каждого узла
- 1Как сделать массив из Google.Apis.Drive.v2.Data.File?
- 1проблема вращения showDialog, когда используются два диалога
- 1Python 2.7 split и .col конкатенация
- 0Какой самый эффективный способ текстовых URL-адресов для 404 ошибок
- 1Как я могу разделить объект между работающей службой и деятельностью
- 1Как распечатать таблицу ASCII?
- 1Python / Pandas — помещает список диктов в DataFrame Pandas — Dict Keys должен быть столбцами
- 1Почему я могу установить любую строку типа события для вызова addEventListener и без setTimeout я теряю свой эффект css?
- 1Как я могу использовать плагин ServiceStack RegistrationFeature с Redis?
- 1Обработка карт всегда вне границ
- 1Android — Настройка обнаружения коллизий растровых изображений после поворота по матрице
- 1Проблема безопасности JavaScript
- 0Ошибка при подключении базы данных mysql
- 0curl не работает для «динамических моделей блогов»
- 0Это всегда дает неопределенную ошибку ссылки
- 1Файл (чтение и запись) неправильно определяет символы newLine + еще
- 1Загрузка библиотеки C в Python, которая закрывает другую библиотеку C — неразрешенный общий символ
- 0Проверка достоверности: уникальный параметр, 4-й параметр
- 0Получить JSON ошибку при звонке с угловой с Zend Framework 1
- 0Как использовать jQuery для выбора этого элемента: <span style = «vertical-align: bottom»>
- 1Twisted: кеш-список экземпляров
- 1Как добавить элементы из строки, добавленной из консоли, в список в Java
- 1Python вызывает metpy.calc.lfc (), поднимает IndexError: индекс 0 выходит за пределы оси 0 с размером 0
- 0Supersized Slide — перейти к конкретному слайду по ссылке
- 1Подписка на шаблон Meteor JS: невозможно запросить данные с помощью find () даже после Template.instance (). SubscriptionReady ()
- 1Окно SWT не закрывается при нажатии контекстного меню
- 1Android r.java не будет обновляться
- 0Флэш-плеер правой кнопкой мыши не имеет настройки можно нажать
- 1WP8.1 командная панель (панель приложения) issticky проблема
- 1Python: для цикла в диапазоне по файлам
- 0Проблема конфигурации opencv 2.4.3 в Visual Studio 2010
- 1Нарисуйте вид с рисунком
- 1Возможно, ошибка в фильтре GeoShape (NEST)
- 0Проверка формы подтверждения магистрали
- 0используйте тег для отправки формы на другую страницу
- 0Как получить значение отформатированного значения ячейки строки в jqgrid
- 1Фильтр с несколькими столбцами в сетке данных
- 0Как исключить файлы из модульного теста
- 0Умный способ перетащить HTML структуру
- 0Соединение с базой данных потеряно — база данных Digital Ocean
- 0Отображение один-ко-многим без дубликатов
- 0Angular — включить / выключить div