用Swift改变占位符文本颜色

我有一个实现深蓝色UITextField的设计,因为占位符文本默认是深灰色的颜色,我几乎不能弄清楚占位符文本说什么。

我当然在谷歌上搜索过这个问题,但我还没有想出一个解决方案,而使用Swift语言而不是Obj-c。

是否有一种方法可以在UITextField中使用Swift更改占位符文本颜色?

242321 次浏览

可以使用由于字符串设置占位符文本。只需要将你想要的颜色传递给attributes参数。

斯威夫特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]
)

斯威夫特3:

myTextField.attributedPlaceholder = NSAttributedString(
string: "Placeholder Text",
attributes: [NSAttributedStringKey.foregroundColor: UIColor.white]
)

年长的迅速:

myTextField.attributedPlaceholder = NSAttributedString(
string: "Placeholder Text",
attributes: [NSForegroundColorAttributeName: UIColor.white]
)

您可以使用Interface Builder快速完成此任务,而无需添加一行代码。

选择UITextField并打开右边的标识检查器:

enter image description here

点击加号按钮,添加一个新的运行时属性:

placeholderLabel.textColor (Swift 4)

_placeholderLabel.textColor (Swift 3或以下)

使用颜色作为类型并选择颜色。

就是这样。

你不会看到结果,直到你再次运行你的应用程序。

要为应用程序中的所有UITextField设置一次占位符颜色,你可以这样做:

UILabel.appearanceWhenContainedInInstancesOfClasses([UITextField.self]).textColor = UIColor.redColor()

这将为整个应用程序中的所有TextField占位符设置所需的颜色。但它只在iOS 9之后可用。

在swift的iOS 9之前没有appearenceWhenContainedIn....()方法,但你可以使用这里提供的解决方案之一在Swift中出现whencontainedin

像这样创建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中。你会看到

enter image description here

这段代码在Swift3中工作:

yourTextFieldName .setValue(UIColor.init(colorLiteralRed: 80/255, green: 80/255, blue: 80/255, alpha: 1.0), forKeyPath: "_placeholderLabel.textColor")

如果你有任何问题,请告诉我。

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
}
}
yourTextfield.attributedPlaceholder = NSAttributedString(string: "your placeholder text",attributes: [NSForegroundColorAttributeName: UIColor.white])

在Swift 3.0中,使用

let color = UIColor.lightText
textField.attributedPlaceholder = NSAttributedString(string: textField.placeholder, attributes: [NSForegroundColorAttributeName : color])

在Siwft 5.0 +使用

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])

为迅速

func setPlaceholderColor(textField: UITextField, placeholderText: String) {
textField.attributedPlaceholder = NSAttributedString(string: placeholderText, attributes: [NSForegroundColorAttributeName: UIColor.pelorBlack])
}

你可以用这个;

self.setPlaceholderColor(textField: self.emailTextField, placeholderText: "E-Mail/Username")

为迅速

创建UITextField扩展

extension UITextField{


func setPlaceHolderColor(){
self.attributedPlaceholder = NSAttributedString(string: self.placeholder!, attributes: [NSForegroundColorAttributeName : UIColor.white])
}
}

如果你是从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!])
}
}
}

添加带属性的占位符:

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)

对于Swift 3和3.1,这工作得非常好:

passField.attributedPlaceholder = NSAttributedString(string: "password", attributes: [NSForegroundColorAttributeName: UIColor.white])

它更多的是个性化你的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/

对于Swift 4.0, X-code 9.1版本或iOS 11,可以使用以下语法来拥有不同的占位符颜色

textField.attributedPlaceholder = NSAttributedString(string: "Placeholder Text", attributes: [NSAttributedStringKey.foregroundColor : UIColor.white])

下面是我对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)

希望它能帮助到一些人!

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!])
}
}
}

Swift 4

txtField1.attributedPlaceholder = NSAttributedString(string: "-", attributes: [NSAttributedStringKey.foregroundColor: UIColor.white])

crubio对Swift 4的答案更新

选择UITextField并在右侧打开标识检查器: . bb0 . UITextField

单击加号按钮并添加一个新的运行时属性:placeholderLabel.textColor(而不是_placeholderLabel.textColor)

使用颜色作为类型并选择颜色。

如果您运行您的项目,您将看到这些更改。

对于swift 4.2及以上版本,你可以这样做:

textField.attributedPlaceholder = NSAttributedString(string: "Placeholder Text", attributes: [NSAttributedString.Key.foregroundColor: UIColor.white])

我很惊讶这里有这么多糟糕的解决方案。

这里有一个永远有效的版本。

斯威夫特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])
}
}
}

提示:如果你在设置颜色后更改占位符文本-颜色将重置。

就我而言,我做了以下事情:

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])
}
}
}
}

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}];

这里我正在写UITextField的所有UIDesignable。在这段代码的帮助下,你可以直接从storyboard中的UI文件Inspector中访问它

@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!])
}
}


}

只需将以下代码写入Appdelegate的didFinishLaunchingWithOptions方法如果你想在整个应用程序中改变,使用这个,该方法是用斯威夫特4.2编写的

UILabel.appearance(whenContainedInInstancesOf: [UITextField.self]).textColor = UIColor.white

在我的例子中,我使用斯威夫特4

我为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(颜色:UIColor.white)

enter image description here

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}];

斯威夫特:

emailTextField.attributedPlaceholder = NSAttributedString(string: "Friend's Email",
attributes: [NSAttributedString.Key.foregroundColor: UIColor.white])

用于更改占位符文本颜色的Objective C代码。

首先导入这个objc/runtime类-

#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];

对于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;


}

在Swift中这样使用,

 let placeHolderText = textField.placeholder ?? ""
let str = NSAttributedString(string:placeHolderText!, attributes: [NSAttributedString.Key.foregroundColor :UIColor.lightGray])
textField.attributedPlaceholder = str

在Objective C中

NSString *placeHolder = [textField.placeholder length]>0 ? textField.placeholder: @"";
NSAttributedString *str = [[NSAttributedString alloc] initWithString:placeHolder attributes:@{ NSForegroundColorAttributeName : [UIColor lightGrayColor] }];
textField.attributedPlaceholder = str;
    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!])
}
}
}

在我的例子中,我必须将占位符设置为黑色。我的UITextField名称是passwordText。下面的代码在斯威夫特5中进行了测试,对我来说工作正常。我也有一个现有的文本对应的占位符。

let placeholderColor = UIColor.black
passwordText.attributedPlaceholder = NSAttributedString(string: passwordText.placeholder!, attributes: [NSAttributedString.Key.foregroundColor : placeholderColor])