简体   繁体   中英

Swift3 UITextField change placeholder font type and size

Code:

txtField.attributedPlaceholder = NSAttributedString(string:strPlaceHolder, attributes:[NSForegroundColorAttributeName:UIColorFromRGB(color:PlaceHolderColor, alpha:1.0),NSFontAttributeName :UIFont(name: "Didot-Italic", size: 4)!])

I am trying to change the UITextField placeholder font type and font size. It is not working. What is wrong with my code? Any help will be appreciated.

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
    txtField.attributedPlaceholder = NSAttributedString(string:"Place holder text in here", attributes:[NSForegroundColorAttributeName: UIColor(red: 153.0/255.5, green: 153.0/255.5, blue: 153.0/255.5, alpha: 0.5)])
}

place holder attribute text will be same as your textfield text attribute in size and font

您应该更改文本字段的字体属性(即 txtField.font),然后设置占位符文本(即 txtField.placeholder)

SWIFT 5 / XCode 11:

UITextField has a property called .attributedPlaceholder you can assign attributes using NSAttributedString Keys. To customize a "searchBoxTextField" placeholder to: light gray text color & Times New Roman font of size 20

try copying/pasting this & it should work...

    override func viewDidLoad() {
        super.viewDidLoad()

        searchBoxTextField.attributedPlaceholder = NSAttributedString(string:"Enter a Word" attributes:[NSAttributedString.Key.foregroundColor: UIColor.lightGray, NSAttributedString.Key.font :UIFont(name: "Times New Roman", size: 20)!])

    }

note: You can still use Auto Layout selections to control the text appearance entered by the user. So in this example, the placeholder is gray, but if you selected black for the textView text color it will transition nicely when the user types into the box.

占位符灰色,小,Times New Roman

用户输入的文本白色、粗体、Futura

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