Xco*_*ode 16 ios xcode7 swift2
如何改变UITextfield placeholder和fontsize在SWIFT 2.0吗?
Kir*_*odi 70
#1.以编程方式设置占位符文本字段颜色
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
Run Code Online (Sandbox Code Playgroud)
要么
txtTitle.attributedPlaceholder = NSAttributedString(string:"Enter Title", attributes: [NSForegroundColorAttributeName: yellowColor])
Run Code Online (Sandbox Code Playgroud)
注意:Name是你的占位符textField.
PlaceHolder TextFiled:
- - - - - - - - - - - - - - - - 要么 - - - - - - - - - --------------------
#2.在运行时属性设置占位符文本字段颜色
设置textfield placeHolder文本 Enter Title
单击textfield属性的标识检查器.
用户定义运行时属性,添加颜色属性
关键路径: _placeholderLabel.textColor
类型: Color
价值: Your Color or RGB value
PlaceHolder TextFiled:
Kir*_*hav 12
针对Swift 3进行了更新
如果要更改Swift 3的UITextField占位符颜色,请使用以下代码行:
let yourTextFieldName = UITextField(frame: CGRect(x: 0, y: 0, width: 180, height: 21))
yourTextFieldName.attributedPlaceholder = NSAttributedString(string: "placeholder text", attributes: [NSForegroundColorAttributeName: UIColor.white])
Run Code Online (Sandbox Code Playgroud)
您可以尝试使用此示例代码
let textFld = UITextField();
textFld.frame = CGRectMake(0,0, 200, 30)
textFld.center = self.view.center;
textFld.attributedPlaceholder = NSAttributedString(string:"Test Data for place holder", attributes:[NSForegroundColorAttributeName: UIColor.blueColor(),NSFontAttributeName :UIFont(name: "Arial", size: 10)!])
self.view.addSubview(textFld)
Run Code Online (Sandbox Code Playgroud)
对于Swift 4.2,请使用NSAttributedString.Key.foregroundColor而不是NSForegroundColorAttributeName
所以就这样
textField.attributedPlaceholder = NSAttributedString(string: "placeholder text", attributes: [NSAttributedString.Key.foregroundColor: UIColor.white])
Run Code Online (Sandbox Code Playgroud)