iPhone UITextField-更改占位符文本颜色
我想更改在UITextField
控件中设置的占位符文本的颜色,以使其变为黑色。
我宁愿在不使用普通文本作为占位符的情况下执行此操作,也不必重写所有方法来模仿占位符的行为。
我相信如果我重写此方法:
- (void)drawPlaceholderInRect:(CGRect)rect
那么我应该能够做到这一点。 但是我不确定如何从此方法中访问实际的占位符对象。
#1楼
我是Xcode的新手,我找到了一种实现相同效果的方法。
我将uilabel放置在所需格式的占位符上,并将其隐藏在
- (void)textFieldDidBeginEditing:(UITextField *)textField
{switch (textField.tag){case 0:lblUserName.hidden=YES;break;case 1:lblPassword.hidden=YES;break;default:break;}
}
我同意它是可以解决的,而不是真正的解决方案,但是从此链接获得的效果是相同的
注意:在iOS 7上仍然可以使用:
#2楼
由于iOS 6在UIViews中引入了属性字符串,因此可以为占位符文本分配颜色,如下所示:
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.
}
#3楼
我需要保持占位符对齐,因此亚当的答案对我来说还不够。
为了解决这个问题,我使用了一个小的变体,希望对您有所帮助:
- (void) drawPlaceholderInRect:(CGRect)rect {//search field placeholder colorUIColor* color = [UIColor whiteColor];[color setFill];[self.placeholder drawInRect:rect withFont:self.font lineBreakMode:UILineBreakModeTailTruncation alignment:self.textAlignment];
}
#4楼
对于使用Monotouch(Xamarin.iOS)的用户,以下是亚当的答案,已翻译为C#:
public class MyTextBox : UITextField
{public override void DrawPlaceholder(RectangleF rect){UIColor.FromWhiteAlpha(0.5f, 1f).SetFill();new NSString(this.Placeholder).DrawString(rect, Font);}
}
#5楼
对于iOS7及以下版本,我能做的最好的事情是:
- (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.heightreturn 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];}
}
#6楼
iOS 6和更高版本在UITextField
上提供了attributedPlaceholder
。 iOS 3.2及更高版本在NSMutableAttributedString
上提供了setAttributes:range:
NSMutableAttributedString
您可以执行以下操作:
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;
#7楼
在iOS7中处理垂直和水平对齐以及占位符的颜色。 drawInRect和drawAtPoint不再使用当前上下文fillColor。
https://developer.apple.com/library/ios/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/CustomTextProcessing/CustomTextProcessing.html
对象
@interface CustomPlaceHolderTextColorTextField : UITextField@end@implementation CustomPlaceHolderTextColorTextField : UITextField-(void) drawPlaceholderInRect:(CGRect)rect {if (self.placeholder) {// color of placeholder textUIColor *placeHolderTextColor = [UIColor redColor];CGSize drawSize = [self.placeholder sizeWithAttributes:[NSDictionary dictionaryWithObject:self.font forKey:NSFontAttributeName]];CGRect drawRect = rect;// verticially align textdrawRect.origin.y = (rect.size.height - drawSize.height) * 0.5;// set alignmentNSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];paragraphStyle.alignment = self.textAlignment;// dictionary of attributes, font, paragraphstyle, and colorNSDictionary *drawAttributes = @{NSFontAttributeName: self.font,NSParagraphStyleAttributeName : paragraphStyle,NSForegroundColorAttributeName : placeHolderTextColor};// draw[self.placeholder drawInRect:drawRect withAttributes:drawAttributes];}
}@end
#8楼
您可以使用以下代码将占位符文本颜色更改为所需的任何颜色。
UIColor *color = [UIColor lightTextColor];
YOURTEXTFIELD.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"PlaceHolder Text" attributes:@{NSForegroundColorAttributeName: color}];
#9楼
也许您想尝试这种方式,但是Apple可能会警告您有关访问私有ivar的信息:
[self.myTextField setValue:[UIColor darkGrayColor] forKeyPath:@"_placeholderLabel.textColor"];
注意
根据MartinAlléus的说法,这不再适用于iOS 7。
#10楼
为什么不只使用UIAppearance
方法:
[[UILabel appearanceWhenContainedIn:[UITextField class], nil] setTextColor:[UIColor whateverColorYouNeed]];
#11楼
简单且无痛苦,对于某些人来说可能是一个简单的选择。
_placeholderLabel.textColor
不建议生产,Apple可能会拒绝您的提交。
#12楼
[txt_field setValue:ColorFromHEX(@"#525252") forKeyPath:@"_placeholderLabel.textColor"];
#13楼
以下仅适用于iOS6 +(如Alexander W的评论所示):
UIColor *color = [UIColor grayColor];
nameText.attributedPlaceholder =[[NSAttributedString alloc]initWithString:@"Full Name"attributes:@{NSForegroundColorAttributeName:color}];
#14楼
类别FTW。 可以进行优化以检查有效的颜色变化。
#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
#15楼
覆盖drawPlaceholderInRect:
是正确的方法,但是由于API(或文档)中的错误而无法使用。
该方法永远不会在UITextField
上调用。
另请参见UITextField上的drawTextInRect未调用
您可以使用digdog的解决方案。 由于我不确定是否能通过Apple审查,因此我选择了另一种解决方案:用我自己的标签覆盖文本字段,以模仿占位符行为。
不过这有点混乱。 代码看起来像这样(注意,我正在TextField的子类中执行此操作):
@implementation PlaceholderChangingTextField- (void) changePlaceholderColor:(UIColor*)color
{ // Need to place the overlay placeholder exactly above the original placeholderUILabel *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;
}
#16楼
在Swift中:
if let placeholder = yourTextField.placeholder {yourTextField.attributedPlaceholder = NSAttributedString(string:placeholder, attributes: [NSForegroundColorAttributeName: UIColor.blackColor()])
}
在Swift 4.0中:
if let placeholder = yourTextField.placeholder {yourTextField.attributedPlaceholder = NSAttributedString(string:placeholder, attributes: [NSAttributedStringKey.foregroundColor: UIColor.black])
}
#17楼
对于iOS 6.0 +
[textfield setValue:your_color forKeyPath:@"_placeholderLabel.textColor"];
希望能帮助到你。
注意: 由于我们正在访问私有API,Apple可能会拒绝(0.01%的机会)您的应用程序。 自两年以来,我在所有项目中都使用了此功能,但Apple并没有要求这样做。
#18楼
在Swift <3.0中可以使用:
myTextField.attributedPlaceholder =
NSAttributedString(string: "placeholder text", attributes: [NSForegroundColorAttributeName : UIColor.redColor()])
在iOS 8.2和iOS 8.3 beta 4中进行了测试。
斯威夫特3:
myTextfield.attributedPlaceholder =
NSAttributedString(string: "placeholder text", attributes: [NSForegroundColorAttributeName : UIColor.red])
斯威夫特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])
#19楼
我已经遇到了这个问题。 就我而言,以下代码是正确的。
目标C
[textField setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];
对于Swift 4.X
tf_mobile.setValue(UIColor.white, forKeyPath: "_placeholderLabel.textColor")
对于iOS 13 Swift代码
tf_mobile.attributedPlaceholder = NSAttributedString(string:"PlaceHolder Text", attributes: [NSAttributedString.Key.foregroundColor: UIColor.red])
您还可以针对iOS 13使用以下代码
let iVar = class_getInstanceVariable(UITextField.self, "_placeholderLabel")!
let placeholderLabel = object_getIvar(tf_mobile, iVar) as! UILabel
placeholderLabel.textColor = .red
希望对您有所帮助。
#20楼
您可以像这样重写drawPlaceholderInRect:(CGRect)rect
来手动呈现占位符文本:
- (void) drawPlaceholderInRect:(CGRect)rect {[[UIColor blueColor] setFill];[[self placeholder] drawInRect:rect withFont:[UIFont systemFontOfSize:16]];
}
#21楼
同样在情节提要中,无需单行代码
#22楼
这样我们就可以在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"];
#23楼
对于具有多种颜色的设置属性文本字段占位符,
只需指定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;
输出:-
#24楼
迅捷版。 可能会帮助某人。
class TextField: UITextField {override var placeholder: String? {didSet {let placeholderString = NSAttributedString(string: placeholder!, attributes: [NSForegroundColorAttributeName: UIColor.whiteColor()])self.attributedPlaceholder = placeholderString}}
}
#25楼
对于Xamarin.iOS开发人员,我从此文档https://developer.xamarin.com/api/type/Foundation.NSAttributedString/中找到了它
textField.AttributedPlaceholder = new NSAttributedString ("Hello, world",new UIStringAttributes () { ForegroundColor = UIColor.Red });
#26楼
另一个不需要子类化的选项-将占位符留空,然后在“编辑”按钮的顶部放置一个标签。 就像管理占位符一样管理标签(用户输入任何内容时清除。)
#27楼
Swift 3.0 +故事板
为了在情节提要中更改占位符颜色,请使用下一个代码创建扩展。 (可以随意更新此代码,如果您认为它可以更清晰,更安全)。
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版本
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版本
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)}}
}
#28楼
在Swift 3中
import UIKitlet TEXTFIELD_BLUE = UIColor.blue
let TEXTFIELD_GRAY = UIColor.grayclass DBTextField: UITextField {/// Tetxfield Placeholder Color@IBInspectable var palceHolderColor: UIColor = TEXTFIELD_GRAYfunc setupTextField () {self.attributedPlaceholder = NSAttributedString(string:self.placeholder != nil ? self.placeholder! : "",attributes:[NSForegroundColorAttributeName: palceHolderColor])}
}class DBLocalizedTextField : UITextField {override func awakeFromNib() {super.awakeFromNib()self.placeholder = self.placeholder}
}
#29楼
迅速3.X
textField.attributedPlaceholder = NSAttributedString(string: "placeholder text", attributes:[NSForegroundColorAttributeName: UIColor.black])
迅速5
textField.attributedPlaceholder = NSAttributedString(string: "placeholder text", attributes: [NSAttributedString.Key.foregroundColor : UIColor.black])
#30楼
Swift 4.1的此解决方案
textName.attributedPlaceholder = NSAttributedString(string: textName.placeholder!, attributes: [NSAttributedStringKey.foregroundColor : UIColor.red])
#31楼
带CAVEAT的Swift 5。
let attributes = [ NSAttributedString.Key.foregroundColor: UIColor.someColor ]
let placeHolderString = NSAttributedString(string: "DON'T_DELETE", attributes: attributes)
txtField.attributedPlaceholder = placeHolderString
请注意,即使在其他代码中设置了该字符串,也必须在“ DON'T_DELETE”所在的位置输入非空String
。 可能会节省您五分钟的时间。
iPhone UITextField-更改占位符文本颜色相关推荐
- iPhone的UITextField-更改占位符文本颜色
我想改变占位符文本我在我的UITextField控件设置的颜色,使其变黑. 我宁愿做这个正常的文本占位符,不得不重写所有模仿一个占位符的行为. 我相信,如果我重写 - (void)drawPlaceh ...
- html用占位符文本填补空白,占位符文本的选择
通过解决占位符的误用,提高表单的可用性 占位符文本可用作几乎所有的HTML输入类型的属性,被误导的设计师和开发人员不要犹豫.为复杂的表单提供文字帮助或者删除输入标签来提高美观度都颇具吸引力,然而,这样 ...
- 如何在Windows 8中更改登录屏幕的颜色
Nearly every component of Windows 8 can be customized to suit your needs, some settings however are ...
- [css] 如何更改placeholder的字体颜色和大小?
[css] 如何更改placeholder的字体颜色和大小? <style>/* Chrome浏览器 */input::-webkit-input-placeholder {color: ...
- iphone复制不能全选_忘记Apple ID密码,如何直接在 iPhone 上更改?
最近有不少同学问我,如果忘记了 Apple ID 的密码,怎么能直接在 iPhone 上修改?别急,我现在就教你如果之前已经在 iPhone 上登录过你的账户,并且已经将 iPhone 设置为「受信任 ...
- Idea更改console控制台 日志颜色(非插件)
Idea更改console控制台 日志颜色(非插件) file-setting-editor-color scheme-console colors 在右侧的选项中可以自定义更改颜色 我之前控制台日志 ...
- 计算机更改桌面,2010年职称计算机考试:更改桌面背景和颜色
Windows XP提供了各种桌面的颜色和背景方案,用户可以根据自己的爱好进行选择.颜 色充当桌面的最底层,背景覆盖于颜色之上. (l)桌面背景的更改 在"显示属性"对话框中,选择 ...
- WOW!今年iPhone XR将新增两种颜色:绿色和薰衣草色
[TechWeb]5月12日消息,据外媒报道,今年iPhone XR将新增两种颜色取代珊瑚色和蓝色,这两种颜色为绿色和薰衣草色. 届时,iPhone XR将有六种颜色可供选择,分别是白色.黑色.黄色和 ...
- android edittext底线,android – 更改edittext的底线颜色
我正在尝试更改EditText的底线颜色,但它显示默认的蓝线颜色.我无法理解我哪里出错了? android:id="@+id/searchtext" android:layout_ ...
最新文章
- LevelDb系列之简介
- 动态导入ECMAScript模块一文看懂
- ISE14.7安装教程(转)
- 燃烧温度计算程序_【知识库】燃气燃烧器如何安全操作?
- php 替换某一行,PHP中如何替换换行符?
- ios查看ipa是否函数特定字符_iOS 中基础字符判断函数收集(如判断大小写、数字等)...
- Errors running builder 'DeploymentBuilder' on project '工程名'
- 【ORACLE】 安装需要注意的问题(一)
- 【转】js之iframe子页面与父页面通信
- 推荐一位BAT数据大神!(附联系方式)
- static和不完全类型的一个例子
- intellij 使用_使用IntelliJ书签
- 两道二分coming~
- javaweb不同用户需要几张表_程序员必备2020版:JavaWeb快速进阶全套教程
- mysql连接数详解_MySQl 修改最大连接数详解
- C#:安装Windows服务,动态指定服务名及描述
- 如何成长为一名专业的程序员?
- php转png在线转换,png转ico在线工具
- Windows7 设置窗口颜色 护眼
- ffmpeg视频切片方案
热门文章
- 算法----两数之和
- UItraIso 制作ubentu 系统失败
- Still unable to dial persistent://blog.csdn.net:80 after 3 attempts
- LyaoutParameters作用
- LFU的多种实现方式,从简单到复杂,新手必看
- 从源码角度分析MapReduce的map-output流程
- Shell引用-逻辑判断
- 【Android UI】theme style
- Flutter开发之ListView添加HeaderView和FooterView-2(39)
- execute taskaction$gradle怎么解决_Spring 源码中设计模式?怎么回答面试官才稳?