SwiftのUITextFieldをカスタムした時に、placeholderのテキストカラーも一緒に設定する

Swift Swift
Swift

UITextFieldのプレースホルダーの設定は簡単にできるのですが、カラーの指定が意外と簡単にできません。。。
※Swiftってそういう所結構ありますよね・・・(・ω・

NSAttributedStringで指定する事で色指定をする事ができるのですが、コードでカスタムしたクラスを作っているのに、使用する時に毎回指定するのは面倒だし、指定を忘れるかもしれない・・・

できればカスタムクラスのコード内で完結したい。
そういう場合の設定方法です。

class CustomTextField: UITextField {

    let padding = UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8)
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        // ここで指定したい所ですが、この段階ではプレースホルダーの内容が無い↓
        let pleaceholderText = self.placeholder ?? ""
        self.attributedPlaceholder = NSAttributedString(string: pleaceholderText, attributes: [NSAttributedString.Key.foregroundColor : UIColor.black])
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    
    override func placeholderRect(forBounds bounds: CGRect) -> CGRect {
        let pleaceholderText = self.placeholder ?? ""
        self.attributedPlaceholder = NSAttributedString(string: pleaceholderText, attributes: [NSAttributedString.Key.foregroundColor : R.color.textColorSettingSub() ?? UIColor.gray])
        return bounds.inset(by: padding)
    }
}

このメソッドの説明は公式サイトをご覧ください。
https://developer.apple.com/documentation/uikit/uitextfield/1619615-placeholderrect

プレースホルダーのテキストが設定されている場合(された時??)に呼ばれるメソッドのようです。
この段階であれば、UITextField(self)のプレースホルダーの内容が取得できるので、ViewControllerで使用する時に、自由にプレースホルダーのテキストを設定して使用する事ができます。

コメント

タイトルとURLをコピーしました