How to change UITextfield placeholder color and fontsize using swift 2.0?

前端 未结 10 649
小蘑菇
小蘑菇 2020-12-28 16:22

How to change UITextfield placeholder & fontsize in SWIFT 2.0?

相关标签:
10条回答
  • 2020-12-28 16:50

    You can try with this sample code

    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)
    
    0 讨论(0)
  • 2020-12-28 16:52

    For swift 4 instead of

    NSForegroundColorAttributeName

    use

    NSAttributedStringKey.foregroundColor

    0 讨论(0)
  • 2020-12-28 16:54

    It's easy to do with a subclass of UITextField.

    Add placeholderColor property to easily set the color, and then observer changing of .placeholder to apply the color to it (with use of .attributedPlaceholder property)

    var placeholderColor: UIColor = .lightGray
    
    override var placeholder: String? {
        didSet {
            let attributes = [ NSAttributedString.Key.foregroundColor: placeholderColor ]
            attributedPlaceholder = NSAttributedString(string: placeholder ?? "", attributes: attributes)
        }
    }
    

    You do need to set the placeholder text programatically for the color to apply.

    0 讨论(0)
  • 2020-12-28 16:57

    #1. set Placeholder textfield color Programmatically

        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
    

    OR

    txtTitle.attributedPlaceholder = NSAttributedString(string:"Enter Title", attributes: [NSForegroundColorAttributeName: yellowColor])
    

    Note : Name is your placeholder of textField.

    PlaceHolder TextFiled :

    -------------------------------- OR -------------------------------------

    #2. set Placeholder textfield color at runtime attribute

    1. Set textfield placeHolder text Enter Title

    2. Click on identity inspector of textfield property.

    3. User Define Runtime Attributes, add color attributes

      Key Path : _placeholderLabel.textColor

      Type : Color

      value : Your Color or RGB value

      PlaceHolder TextFiled :

    0 讨论(0)
提交回复
热议问题