繁体   English   中英

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

[英]UITextField Placeholder and Text Size should be separate - Swift

我的要求是,当文本字段的占位符可见时,其颜色应为灰色且字体大小为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的占位符。 现在尝试了几个小时。 任何帮助将不胜感激。

只需尝试这段代码,执行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)!
        }
    }

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

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

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

textField.attributedPlaceholder = ...

只需尝试使用以下代码即可进一步帮助您:

    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

将此代码尝试到您的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)!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM