我的要求是,当文本字段的占位符可见时,其颜色应为灰色且字体大小为10,但是当用户开始在文本字段中键入内容时,其颜色应为黑色且字体大小为14。我已经尝试过: / p>
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的占位符。现在尝试了几个小时。任何帮助将不胜感激。
答案 0 :(得分:2)
只需尝试以下代码,请执行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 :(得分:1)
在设置字体后简单地设置占位符,因为设置字体也适用于占位符(请参见https://developer.apple.com/documentation/uikit/uitextfield/1619604-font):
textField.font = ...
textField.textColor = ...
textField.attributedPlaceholder = ...
答案 2 :(得分:0)
只需尝试以下代码即可进一步帮助您
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
答案 3 :(得分:0)
在您的 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)!