简体   繁体   中英

UITextField Placeholder and Text Size should be separate - Swift

My requirement is such that when placeholder of textfield is visible then its color should be gray and font size 10, but when user starts typing into the textfield, its color should be black and font size 14. I have tried this:

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

But, my placeholder font size is getting overridden by textfield.font , so I am unable to get placeholder of size 10. Where am I going wrong? Tried this for couple of hours now. Any help will be appreciated.

Just try this code, take the UITextFieldEditingChanged action outlet and use as below.

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

If any doubt please comment ].

Simply set the placeholder after setting the font since setting the font also applies to the placeholder (see https://developer.apple.com/documentation/uikit/uitextfield/1619604-font ):

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

textField.attributedPlaceholder = ...

Just try this code may help you for further:

    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

Try this code into your viewDidLoad() method:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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