UITextField 的提示語placeholder 多行顯示

公司的新app有多語言, 登錄注冊的UITextField提示語多語言情況下顯示不全, 所以需求是提示語多行,輸入還是單行

測試提了bug 不得不改啊

思路: UITextField的placeholder 所在的label沒有公開, 只能寫替代的了

來個(gè)繼承UITextField的類

1.來個(gè)UILabel, 比方叫placeHolderLael., 設(shè)置好?textColor,?textAlignment,?font, 一般placeholder不會太長?numberOfLines設(shè)置為2, 防止超級長的顯示不了?adjustsFontSizeToFitWidth設(shè)置true

2.?override 下?placeholder, 在didSet里面?placeHolderLabel.text = placeholder, ?然后把固有的 設(shè)置clear顏色?attributedPlaceholder = NSAttributedString(string: "", attributes: [NSAttributedString.Key.foregroundColor: UIColor.clear, NSAttributedString.Key.font: UIFont.regularAuto(14)])

3. ?init里面?addSubview(placeHolderLabel) frame和UITextField設(shè)置一致

4. 加一個(gè)textDidChangeNotification的通知, 方法里面顯示隱藏, 此處注意判斷是否是自己.

5. 后臺發(fā)現(xiàn)?UITextField還要在切換郵箱手機(jī)的時(shí)候 "復(fù)用",?override 下 text, 處理隱藏顯示


代碼如下(代碼復(fù)制進(jìn)簡書的編輯里面 變的好慘 有啥技巧嗎? ):

class LanguagesTextFeild: UITextField {

? ? lazy var placeHolderLabel: UILabel = {

? ? ? ? let?v = UILabel()

? ? ? ? v.textColor = .gray

? ? ? ? v.textAlignment = .left

? ? ? ? v.font = UIFont.systemFont(ofSize:14)

? ? ? ? v.numberOfLines = 2

? ? ? ? v.adjustsFontSizeToFitWidth = true

? ? ? ? return?v

? ? }()


? ? override?var?placeholder: String? ?{

? ? ? ? didSet{

? ? ? ? ? ? placeHolderLabel.text = placeholder

? ? ? ? ? ? attributedPlaceholder = NSAttributedString(string: "", attributes: [NSAttributedString.Key.foregroundColor: UIColor.clear, NSAttributedString.Key.font: UIFont.regularAuto(14)])

? ? ? ? }

? ? }?

override?var?text: String? {

? ? ? ? didSet{

? ? ? ? ? ? handle()

? ? ? ? }

? ? }

? ? override?init?(frame: CGRect) {

? ? ? ? super.init(frame: frame)

? ? ? ? addSubview(placeHolderLabel)

? ? ? ? placeHolderLabel.snp.makeConstraints { make in

? ? ? ? ? ? make.edges.equalToSuperview()

? ? ? ? }

? ? ? ? NotificationCenter.default.addObserver(self, selector:#selector(textChanged), name:UITextField.textDidChangeNotification, object:nil)

? ? }

? ? @objc?func?textChanged(_?nf: Notification?) {

? ? ? ? guard?let?tf = nf?.object, tf?as! LanguagesTextFeild ==?self?else{

? ? ? ? ? ? return

? ? ? ? }

? ? ? ?handle()

? ?}


? ? fun chandle() {

? ? ? ? if?let?t = text {

? ? ? ? ? ? placeHolderLabel.isHidden = t.count>0

? ? ? ? }?else?{

? ? ? ? ? ? placeHolderLabel.isHidden =?false

? ? ? ? }

? ? }


? ? required?init?(coder: NSCoder) {

? ? ? ? fatalError("init(coder:) has not been implemented")

? ? }

}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容