UITextField的占位符和文本大小应该分开 - Swift

3

我的要求是,当文本框的占位符可见时,其颜色应为灰色,字号为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的占位符。我做错了什么?现在尝试了几个小时了,任何帮助将不胜感激。
4个回答

4

3

尝试将以下代码放入您的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)!

1

尝试使用以下代码,获取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)!
        }
    }

如果有任何疑问,请评论。


1

只需尝试此代码,可能会有助于您进一步了解:

    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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接