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

RxSwift - Giới thiệu

Bạn có nghe qua về Reactive Programming chưa, đây là một khái niệm lập trình hoàn toàn mới. “Reactive Programming là lập trình theo hướng bất đồng bộ các dòng chảy dữ liệu(data streams)” Sau khi đọc khái niệm các bạn có lẽ rất mơ hồ, vậy các data streams là gì. Vậy để mình ví dụ cho các bạn: - Trong lập trình bình thường ( imperative programming ) a = b + c , tức a được gắn với kết quả cộng của b và c .Khi b với c thay đổi thì tất nhiên sẽ không ảnh hưởng tới a, nhưng trong Reactive Programming này a sẽ tự động thay đổi khi b hoặc c thay đổi, kết quả của a sẽ lập tức thay đổi theo. Vậy tại sao nên dùng RXSwift: + Giúp ứng dụng của bạn hoạt động 1 cách như là real time update ui khi có thay đổi data flow, mang đến trải nghiệm tuyệt vời cho User. + Dễ dàng lập trình bất đồng bộ (Async) thay vì phải dùng : callbacks, delegates, notifications, kvo… Bạn phải dùng nhiều thứ gây ra ứng dụng của bạn phức tạp, khó kiểm soát. + Chuyển đổi các thread khi thực hiện 1 cách...

Swift GCD part 1: Thread safe singletons

Preview Singletons are entities, referenced to the same instance of a class from everywhere in your code. It doesn't matter if you like them or not, you will definitely meet them, so it's better to understand how they work. Constructing and handling a set of data doesn't seem to be a big challenge at first glance. The problems appear when you try to optimise the user experience with background work and your app starts acting weird. ??‍♂️ After decades of watching your display mostly with a blank face, you finally realize that your data isn't handled consistently by the manager because you're accessing it (running tasks on it) from multiple threads at the same time. So you really do have to deal with making your singletons thread safe. This article series is dedicated to thread handling using Swift. In the first part below you will get a comprehensive insight into som...

Enum Initializers

In Swift Talk 45 , we wrote a small library for parsing routes. We represented routes as enums, and added a custom initializer to parse routes: enum Route { case home case users(id: Int ) } extension Route { init ?(path: String ) { if path == "/" { self = .home } else if path.hasPrefix( "/users" ) { self = .users(id: 1 ) } else { return nil } } } Of course, this code isn’t complete (see the full public episode for that). Today, we want to focus on assigning to self inside the initializer. In the initializer of any struct or enum we can treat self as a mutable variable (as if it were declared using inout ). This is why we can do the following: enum Result < A > { case success( A ) case error( Error ) } extension Result { init ( _ value: A ) { self = .success(value) } } We can even do this in a struct, although it’s easie...