Skip to main content

How to change placeholder color using Swift


Introduction

Chắc hẳn mỗi chúng ta đều đã thao tác với UITextField và đã quá quen với khái niệm Placeholder của UITextField. Mặc định iOS quy định màu của placeHolder text là màu xám dạng inactive tuy nhiên trong nhiều trường hợp chúng ta cần thay đổi màu này theo design. Trong bài biết này, chúng ta cùng nghiên cứu về cách custom color cho placeholder
Chúng ta cùng tìm hiểu nhé!

What is a placeholder?

Placeholder là một chuỗi charactor, work hoặc string chúng sử dụng để gợi ý nội dung cho phần textbox khi giá trị của ô textbox đang trống. Ví dụ: người sử dụng cần biết loại của giá trị ô cần nhập thế nào là hợp lệ và placeholder giúp user hiểu được điều này dễ hơn.

Change placeholder color with Swift

Sau khi bạn đã kéo IBoutlet cho UITextField trong file Main.Storyboard. Chúng ta kết nối outblet trong file .storyboard với file swift và đặt tên là textFieldWithPlaceholder
@IBOutlet weak var textFieldWithPlaceholder: UITextField!
Và trong ViewDidLoad() chúng ta set placeholder như sau:
var placeHolder = NSMutableAttributedString()
let Name  = "Placeholder Text" 
       
// Set the Font 
placeHolder = NSMutableAttributedString(string:Name, attributes: [NSFontAttributeName:UIFont(name: "Helvetica", size: 15.0)!])

// Set the color
placeHolder.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range:NSRange(location:0,length:Name.characters.count))   

// Add attribute        
textFieldWithPlaceholder.attributedPlaceholder = placeHolder
Sau đó build và run app bạn sẽ nhìn thấy placeholder đã thay đổi font và color theo như đã được setup trong code.

Use Swift Extension to change Placeholder Color

Với cách làm này, chúng ta sẽ tạo một extension cho tất cả các Textfield. Trước tiên chúng ta chọn Text Field trong Viewcontroller, đi tới attributes inspector và set placeholder.

Bạn có thể thấy là tôi đã đánh text "E-mail Address" và tất nhiên bạn có thể hoàn toàn thay thế bằng text khác. Sau đó quay trở lại file ViewController.Swift, chúng ta insert dòng code dưới đây:
extension UITextField{
    @IBInspectable var placeHolderColor: UIColor? {
        get {
            return self.placeHolderColor
        }
        set {
            self.attributedPlaceholder = NSAttributedString(string:self.placeholder != nil ? self.placeholder! : "", attributes:[NSForegroundColorAttributeName: newValue!])
        }
    }
}
Tất nhiên phần extension chúng ta sẽ đặt ngoài phần khai báo cho class như dưới đây:
import Foundation

class ViewController: UIViewController {

    @IBOutlet weak var textFieldWithPlaceholder: UITextField!
    override func viewDidLoad() {
        // stuff
    }
}

extension UITextField{
    @IBInspectable var placeHolderColor: UIColor? {
        get {
            return self.placeHolderColor
        }
        set {
            self.attributedPlaceholder = NSAttributedString(string:self.placeholder != nil ? self.placeholder! : "", attributes:[NSForegroundColorAttributeName: newValue!])
        }
    }
}
Bây giờ, chúng ta quay lại file Main.Storyboard và click vào một trong các UITextFields trong viewcontroller. Sau đó đi tới Attributes Inspector và chúng ta thấy thêm option set color cho UITextField.

User Defined Runtime Attributes

Và cuối cùng đây là giải pháp đơn giản nhất mà bạn không cần phải thêm bất cứ dòng code nào. Chúng ta đi tới UITextField sau đó chọn Identity Inspector và cuộn xuống tới User Defined Runtime Attributes:

Click button "+" và thêm key và value như dưới đây:
Key Path Type Value
_placeholderLabel.textColor Color Select a color
Và sau đó run app bạn sẽ thấy kết quả ngay lập tức.

Conclusion

Trong bài viết này mình đã giới thiệu tới các bạn các cách làm khác nhau để có thể dễ dàng thay đổi color cho placeholder. Tuỳ vào từng bài toán thực tế chúng ta sẽ lựa chọn các cách khác nhau cho phù hợp.
Cám ơn bạn đã dành thời gian cho bài viết này!
Nguồn:
[https://www.ios-blog.com/tutorials/swift/how-to-change-the-placeholder-color-using-swift-extensions-or-user-defined-runtime-attributes/)

Comments

Popular posts from this blog

Alamofire vs URLSession

Alamofire vs URLSession: a comparison for networking in Swift Alamofire and URLSession both help you to make network requests in Swift. The URLSession API is part of the foundation framework, whereas Alamofire needs to be added as an external dependency. Many  developers  doubt  whether it’s needed to include an extra dependency on something basic like networking in Swift. In the end, it’s perfectly doable to implement a networking layer with the great URLSession API’s which are available nowadays. This blog post is here to compare both frameworks and to find out when to add Alamofire as an external dependency. Build better iOS apps faster Looking for a great mobile CI/CD solution that has tons of iOS-specific tools, smooth code signing, and even real device testing? Learn more about Bitrise’s iOS specific solutions! This shows the real power of Alamofire as the framework makes a lot of things easier. What is Alamofire? Where URLSession...

Swift Tool Belt, Part 1: Adding a Border, Corner Radius, and Shadow to a UIView with Interface Builder

During my iOS work, I’ve assembled a set of code that I bring with me on every iOS project. I’m not talking about large frameworks or CocoaPods here. These are smaller Swift extensions or control overrides that are applicable to many projects. I think of them as my tool belt. In this post, I’ll show you an extension that will add a border, a corner radius, and a shadow to any UIView, UIButton, or UILabel and allow you to preview what it will look like in Interface Builder. Back in 2014, I wrote a blog post on Expanding User-Defined Runtime Attributes in Xcode where I added a border, corner radius, and shadow to a UIView using Interface Builder’s user-defined runtime attributes. This solution had no type checking—you had to type the property you wanted to modify by hand and often had to look up what it was called. You also had to run your project in order to see the effect of the runtime attribute. Starting with Xcode 6 , there is a new mech...

Frame vs Bounds in iOS

This article is a repost of an answer I wrote on Stack Overflow . Short description frame = a view’s location and size using the parent view’s coordinate system ( important for placing the view in the parent) bounds = a view’s location and size using its own coordinate system (important for placing the view’s content or subviews within itself) Details To help me remember frame , I think of a picture frame on a wall . The picture frame is like the border of a view. I can hang the picture anywhere I want on the wall. In the same way, I can put a view anywhere I want inside a parent view (also called a superview). The parent view is like the wall. The origin of the coordinate system in iOS is the top left. We can put our view at the origin of the superview by setting the view frame’s x-y coordinates to (0, 0), which is like hanging our picture in the very top left corner of the wall. To move it right, increase x, to move it down increase y. To help me remember bound...