如何使用swift 2.0更改UITextfield占位符颜色和fontsize?

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.在运行时属性设置占位符文本字段颜色

  1. 设置textfield placeHolder文本 Enter Title

    在此输入图像描述

  2. 单击textfield属性的标识检查器.

    在此输入图像描述

  3. 用户定义运行时属性,添加颜色属性

    关键路径: _placeholderLabel.textColor

    类型: Color

    价值: Your Color or RGB value

    在此输入图像描述

    PlaceHolder TextFiled:

    在此输入图像描述

  • 现在(对于 swift 5,13.4.1)它应该是 placeholderLabel.textColor 而不是 _placeholderLabel.textColor (7认同)

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)


小智 10

对于swift 4而不是

NSForegroundColorAttributeName

使用

NSAttributedStringKey.foregroundColor


Jam*_*mil 6

您可以尝试使用此示例代码

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)


Jin*_*Jin 5

对于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)