使用 Swift 更改占位符文本颜色 [英] Changing Placeholder Text Color with Swift

查看:18
本文介绍了使用 Swift 更改占位符文本颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

I have a design that implements a dark blue UITextField, as the placeholder text is by default a dark grey colour I can barely make out what the place holder text says.

I've googled the problem of course but I have yet to come up with a solution while using the Swift language and not Obj-c.

Is there a way to change the placeholder text colour in a UITextField using Swift?

解决方案

You can set the placeholder text using an attributed string. Just pass the color you want to the attributes parameter.

Swift 5:

let myTextField = UITextField(frame: CGRect(x: 0, y: 0, width: 200, height: 30))
myTextField.backgroundColor = .blue
myTextField.attributedPlaceholder = NSAttributedString(
    string: "Placeholder Text",
    attributes: [NSAttributedString.Key.foregroundColor: UIColor.white]
)

Swift 3:

myTextField.attributedPlaceholder = NSAttributedString(
    string: "Placeholder Text",
    attributes: [NSAttributedStringKey.foregroundColor: UIColor.white]
)

Older Swift:

myTextField.attributedPlaceholder = NSAttributedString(
    string: "Placeholder Text",
    attributes: [NSForegroundColorAttributeName: UIColor.white]
)

这篇关于使用 Swift 更改占位符文本颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆