12/08/2018, 16:46

How to change the placeholder color in UITextField

Trong bài này tôi sẽ giới thiệu tới các bạn những cách để thay đổi placeholder color trong UITextField. Đầu tiên là thay đổi giá trị attributed placeholer, tiếp đến là sử dụng extension và cuối cùng là sử dụng User Defined Runtime Attributes. Placeholder là gì? Placeholder trong UITextField là ...

Trong bài này tôi sẽ giới thiệu tới các bạn những cách để thay đổi placeholder color trong UITextField. Đầu tiên là thay đổi giá trị attributed placeholer, tiếp đến là sử dụng extension và cuối cùng là sử dụng User Defined Runtime Attributes.

Placeholder là gì?

Placeholder trong UITextField là một character, word hay một string được sử dụng để gợi nhắc nội dung cần được input vào. Khi user input vào thì placeholder này tự động mất đi để nhường chỗ cho giá trị của user. ví dụ: Trường email: placehoder = "E-mail address"

Thay đổi value của attributedPlaceHolder:

Trong ViewController tạo 1 IBOutlet cho UITextField trong Main.storyBoard:

        @IBOutlet weak var textFieldWithPlaceholder: UITextField!

Trong viewDidLoad() insert:

        var placeHolder = NSMutableAttributedString()
        let placeHolderText  = "E-mail address"

        // Set the Font
        placeHolder = NSMutableAttributedString(string:placeHolderText, attributes: [NSFontAttributeName:UIFont(name: "Helvetica", size: 20.0)!])
        
        // Set the color
        placeHolder.addAttribute(NSForegroundColorAttributeName, value: UIColor.red, range:NSRange(location:0,length:placeHolderText.characters.count))
        
        // Add attribute
        textFieldWithPlaceholder.attributedPlaceholder = placeHolder

Run và xem kết quả.

Sử dụng Swift Extension:

  1. Đầu tiên remove đoạn code trên trong viewDidLoad().
  2. Vào Main.storyBoard -> select UITextField -> select Show the attributes inpector -> Set placeholder text = "E-mail address".
  3. Tạo extension UITextField với @IBInspectable placeHolderColor trong ViewController
extension UITextField{
    @IBInspectable var placeHolderColor: UIColor? {
        get {
            return self.placeHolderColor
        }
        set {
            self.attributedPlaceholder = NSAttributedString(string:self.placeholder != nil ? self.placeholder! : "", attributes:[NSForegroundColorAttributeName: newValue!])
        }
    }
}
  1. Quay lại Main.storyBoard -> select Color in placeHolderColor.
  2. Run và xem kết quả.

Sử dụng User Defined Runtime Attributes:

Cuối cùng, đây là cách đơn giản và nhanh gọn nhất.             </div>
            
            <div class=

0