【问题标题】:UITextField Placeholder and Text Size should be separate - SwiftUITextField 占位符和文本大小应该分开 - Swift
【发布时间】:2019-01-29 22:42:39
【问题描述】:

我的要求是,当文本字段的占位符可见时,它的颜色应该是灰色,字体大小为 10,但是当用户开始在文本字段中输入时,它的颜色应该是黑色,字体大小为 14。我试过这个:

textField.attributedPlaceholder = NSAttributedString(string: placeholderText,
                                                    attributes: [NSAttributedString.Key.foregroundColor: Color.iPhoneGrayColor, NSAttributedString.Key.font: UIFont(name: "SourceSansPro-Regular", size: 10)!])
    textField.textColor = UIColor.black
    textField.font = UIFont(name: "SourceSansPro-Regular", size: 14)!

但是,我的占位符字体大小被textfield.font 覆盖,所以我无法获得大小为 10 的占位符。我哪里出错了?现在尝试了几个小时。任何帮助将不胜感激。

【问题讨论】:

    标签: ios swift uitextfield


    【解决方案1】:

    在设置字体之后只需设置占位符,因为设置字体也适用于占位符(请参阅https://developer.apple.com/documentation/uikit/uitextfield/1619604-font):

    textField.font = ...
    textField.textColor = ...
    
    textField.attributedPlaceholder = ...
    

    【讨论】:

      【解决方案2】:

      在您的 viewDidLoad() 方法中尝试此代码:

      textField.attributedPlaceholder = NSAttributedString(string: placeholderText, attributes: [NSAttributedString.Key.foregroundColor: Color.iPhoneGrayColor, NSAttributedString.Key.font: UIFont(name: "SourceSansPro-Regular", size: 10)!])
          textField.textColor = UIColor.black
          textField.font = UIFont(name: "SourceSansPro-Regular", size: 14)!
      

      【讨论】:

        【解决方案3】:

        试试这段代码,取 UITextFieldEditingChanged 动作出口并使用如下。

        @IBAction func nameTextFieldEditingChanged(_ sender: UITextField) {
                if sender.text?.isEmpty ?? true {
                    //placeholder text size set here
                    textField.font = UIFont(name: "SourceSansPro-Regular", size: 10)!
                } else {
                    // When user starting typing
                    textField.textColor = UIColor.black
                    textField.font = UIFont(name: "SourceSansPro-Regular", size: 14)!
                }
            }
        

        如有疑问请评论]。

        【讨论】:

          【解决方案4】:

          试试这个代码可能会帮助你进一步:

              var myMutableStringTitle = NSMutableAttributedString()
              let Name  = "Enter Title" // PlaceHolderText
          
              myMutableStringTitle = NSMutableAttributedString(string:Name, attributes: [NSFontAttributeName:UIFont(name: "Georgia", size: 20.0)!]) // Font
              myMutableStringTitle.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range:NSRange(location:0,length:Name.characters.count))    // Color
              txtTitle.attributedPlaceholder = myMutableStringTitle
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2016-02-21
            • 1970-01-01
            • 1970-01-01
            • 2011-10-09
            • 2016-05-10
            • 2023-04-11
            • 2014-02-17
            相关资源
            最近更新 更多