【问题标题】:Changing Placeholder Text Color with Swift使用 Swift 更改占位符文本颜色
【发布时间】:2014-11-22 10:31:23
【问题描述】:

我的设计实现了深蓝色 UITextField,因为占位符文本默认为深灰色,我几乎看不出占位符文本的含义。

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

有没有办法使用 Swift 更改 UITextField 中的占位符文本颜色?

【问题讨论】:

    标签: ios swift uikit


    【解决方案1】:

    您可以使用attributed string 设置占位符文本。只需将您想要的颜色传递给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]
    )
    

    【讨论】:

    • iOS 11 SDK - 键没有foregroundColor : self.emailTextField?.attributedPlaceholder = NSAttributedString(string: "placeholder text", attributes: [NSAttributedStringKey.foregroundColor: UIColor.white])
    • @vacawama 。感谢您的交流。遗留项目,从 App Store 更新了我的 Xcode - 版本 9.0 (9A235),最后想出了 self.passwordTextField?.attributedPlaceholder = NSAttributedString(string: "PASSWORD", attributes: [NSForegroundColorAttributeName: UIColor.white]) 的解决方案
    • 对于 iOS 11 SDK 使用 myTextField.attributedPlaceholder = NSAttributedString(string: "placeholder text", attributes: [NSForegroundColorAttributeName: UIColor.white])
    • 有没有不设置字符串就可以设置颜色的方法?
    • @ScottyBlades,您必须使用字符串设置颜色。如果要更改当前属性字符串的颜色,获取当前字符串并使用它创建一个新的:myTextField.attributedPlaceholder = NSAttributedString(string: myTextField.attributedPlaceholder?.string ?? "", attributes: [NSAttributedString.Key.foregroundColor: UIColor.red])
    【解决方案2】:

    就我而言,我必须将占位符设置为黑色。我的UITextField 的名字是passwordText。下面的代码在 Swift 5 中进行了测试,对我来说运行良好。我也有相应占位符的现有文本。

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

    【讨论】:

      【解决方案3】:
          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!])
                      }
                  } 
      }
      

      【讨论】:

        【解决方案4】:

        在 Swift 中这样使用,

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

        在目标 C 中

        NSString *placeHolder = [textField.placeholder length]>0 ? textField.placeholder: @"";
        NSAttributedString *str = [[NSAttributedString alloc] initWithString:placeHolder attributes:@{ NSForegroundColorAttributeName : [UIColor lightGrayColor] }];
        textField.attributedPlaceholder = str;
        

        【讨论】:

          【解决方案5】:

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

          【讨论】:

            【解决方案6】:

            斯威夫特 4:

            txtControl.attributedPlaceholder = NSAttributedString(string: "Placeholder String...",attributes: [NSAttributedStringKey.foregroundColor: UIColor.gray])
            

            目标-C:

            UIColor *color = [UIColor grayColor];
            txtControl.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"Placeholder String..." attributes:@{NSForegroundColorAttributeName: color}];
            

            【讨论】:

              【解决方案7】:

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

              【讨论】:

                【解决方案8】:

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

                首先导入这个 objc/runtime 类 -

                #import <objc/runtime.h>

                然后替换您的文本字段名称 -

                Ivar ivar =  class_getInstanceVariable([UITextField class], "_placeholderLabel");
                UILabel *placeholderLabel = object_getIvar(YourTxtField, ivar);
                placeholderLabel.textColor = [UIColor whiteColor];

                【讨论】:

                  【解决方案9】:

                  对于目标 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])
                  

                  【讨论】:

                    【解决方案10】:

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

                    选择UITextField并打开右侧的身份检查器:

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

                    placeholderLabel.textColor (Swift 4)

                    _placeholderLabel.textColor(Swift 3 或更低版本)

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

                    就是这样。

                    在您再次运行您的应用之前,您不会看到结果。

                    【讨论】:

                    • 是的,但这是一种 hack,因为 placeholderLabel.textColor 属性是私有的...
                    • 应用程序会因为我们使用类的私有属性而被拒绝吗?
                    • 不幸的是,这似乎至少在 iOS 10 上不起作用。
                    • @nickdnk 不正确。现在我已经在 iOS 10.2.1 上进行了测试,并且可以正常工作。 :)
                    • 如果 Apple 将更改内部实现,那么意外崩溃的好方法。)
                    【解决方案11】:

                    就我而言,我使用 Swift 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)

                    【讨论】:

                      【解决方案12】:

                      只需将以下代码写入 Appdelegate 的 didFinishLaunchingWithOptions 方法中如果您想在整个应用中进行更改,请使用此代码,用 Swift 4.2

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

                      【讨论】:

                        【解决方案13】:

                        我在这里编写 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!])
                            }
                        }
                        
                        }
                        

                        【讨论】:

                          【解决方案14】:

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

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

                          【讨论】:

                            【解决方案15】:

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

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

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

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

                            【讨论】:

                              【解决方案16】:

                              对于斯威夫特

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

                              【讨论】:

                                【解决方案17】:

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

                                【讨论】:

                                • ⚠️ 警告:如果您决定读取属性placeHolderColor,此扩展将崩溃您的程序!如果从属性的 getter 返回计算属性本身的值,则将在 getter 内再次调用 getter,从而导致无限递归。 (见:stackoverflow.com/a/42334711/2062785
                                • 要解决这个问题并获得预期的行为(即正确的占位符颜色),请获取attributedString 的第一个字母(如果不为空)并返回其文本颜色,否则返回nil。跨度>
                                • 为什么盒子里有两种颜色。我以为这是暗模式,但事实并非如此。
                                • @asreerama 这就是xcode显示透明色的方式。
                                【解决方案18】:

                                对于 swift 4.2 及更高版本,您可以按以下方式进行操作:

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

                                【讨论】:

                                  【解决方案19】:

                                  要为应用中的所有UITextField 设置一次占位符颜色,您可以执行以下操作:

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

                                  这将为整个应用程序中的所有TextField 占位符设置所需的颜色。但它仅从 iOS 9 开始可用。

                                  在 iOS 9 之前没有出现 swift 中出现的 AppearenceWhenContainedIn....() 方法,但您可以使用此处提供的解决方案之一appearanceWhenContainedIn in Swift

                                  【讨论】:

                                  • 这不仅会改变占位符颜色,还会改变文本颜色。
                                  【解决方案20】:

                                  Swift 3(可能是 2),你可以覆盖 UITextField 子类中占位符上的 didSet 以对其应用属性,这样:

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

                                  【讨论】:

                                    【解决方案21】:

                                    更多的是关于个性化您的文本字段,但无论如何我会分享从另一个页面获取的这段代码并让它变得更好:

                                    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/

                                    【讨论】:

                                      【解决方案22】:

                                      对于 Swift 4

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

                                      【讨论】:

                                      • 这是几个早期答案的副本。无需发布重复的答案。
                                      【解决方案23】:

                                      crubio 对 Swift 4 的回答更新

                                      Select the UITextField and open the identity inspector on the right:

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

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

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

                                      【讨论】:

                                        【解决方案24】:

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

                                        【讨论】:

                                        • 这行不通。 getter 会导致无限递归。
                                        • 这在 swift 4 中运行良好。我在代码中设置了断点并检查了它。无限递归没有发生。
                                        • 不要使用这个。这将导致无限递归。尝试:打印(textField.placeHolderColor)
                                        【解决方案25】:

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

                                        希望它对某人有所帮助!

                                        【讨论】:

                                        • Swift 4.2: self.attributedPlaceholder = NSAttributedString(string: placeholderText, attributes: [NSAttributedString.Key.foregroundColor : color])
                                        【解决方案26】:

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

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

                                        【讨论】:

                                          【解决方案27】:

                                          对于 Swift 3 和 3.1,这非常有效:

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

                                          【讨论】:

                                            【解决方案28】:

                                            使用它来添加属性占位符:

                                            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)
                                            

                                            【讨论】:

                                              【解决方案29】:

                                              对于斯威夫特

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

                                              你可以用这个;

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

                                              【讨论】:

                                                【解决方案30】:
                                                yourTextfield.attributedPlaceholder = NSAttributedString(string: "your placeholder text",attributes: [NSForegroundColorAttributeName: UIColor.white])
                                                

                                                【讨论】:

                                                  猜你喜欢
                                                  • 2017-05-18
                                                  • 2013-02-04
                                                  • 2010-11-23
                                                  • 1970-01-01
                                                  • 1970-01-01
                                                  • 2019-12-09
                                                  • 2023-02-06
                                                  • 2017-10-03
                                                  相关资源
                                                  最近更新 更多