LoginSignup
0
0

More than 5 years have passed since last update.

取得 UITextField 預設 placeholder 的顏色 (算是未完成)

Posted at

從以前開始關於這個 placeholder 的顏色眾說紛紜
雖然說看起來像是「淡灰色」,但是實際上感覺又是有點偏藍的顏色

最近幫 UITextView 加上 placeholder 的 extension
就決定來看看他到底是什麼顏色,
然後幫他寫個擴充

網路上說的顏色

光這一串就超多說法 XDD

裡面有一個算是最接近

UIColor(red: 0, green: 0, blue: 0.0980392, alpha: 0.22)

恩,果然是藍色!
但是實際用了之後還是有點差別:

image.png

下面的明顯地稍微深了一點點
果然還是不行

那就直接拿 UITextFieldView 的 placeholder 來用吧

很可惜不管怎麼拿無法直接拿到這個值
如果真的有的話請留言告訴我 :pray:

先下中斷點看值

let textField = UITextField()
textField.placeholder = "dummy"
var range = NSRange(location: 0, length: 1)
let color = textField.attributedPlaceholder?.attribute(.foregroundColor,
                                                       at: 0,
                                                       effectiveRange: &range) as? UIColor

在 iOS 12.1 的時候這個 color 長這樣:

image.png

holy!! XDD

所以上面提到的 0.0980392 其實已經近似值了只是實際上已經到小數點下不知道幾位去了(笑)

這時候就出現兩的選項了

① 把那個小數點以下不知道幾位的數值做成一個 UIColor 常數
② 直接拿這個 UIColor 來用

後來我選了 ② ,原因是不知道哪個版本他的 placeholder 可能又會偷偷改;拿這個顏色需要的初始化成本也不會很高所以就用下去了!

成果

於是把它寫成 UITextField 的 extension ,要取用會比較直觀方便

//
//  UITextField+Extensions.swift
//  Written in Swift 4.2
//

import UIKit

extension UITextField {
    // 這樣寫的話,整個 app 的生命週期這個方法只會被呼叫到一次而已
    static let defaultPlaceholderColor = fetchPlaceholderColor()

    private static func fetchPlaceholderColor() -> UIColor? {
        let textField = UITextField()
        textField.placeholder = "dummy"
        var range = NSRange(location: 0, length: 1)
        let color = textField.attributedPlaceholder?.attribute(.foregroundColor,
                                                               at: 0,
                                                               effectiveRange: &range) as? UIColor
        return color
    }
}

使用方法

因為我把它宣告成 static 變數 (or say class property) ,在使用的時候就只要這樣即可:

let color = UITextField.defaultPlaceholderColor

成果

Before After
image.png image.png

雖然更接近了,但是不知道為什麼拉近仔細看但是還是有點微妙的差別(笑)
感覺還有另外加入其他 attributes ,再繼續挖挖看 XDDDDD

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0