公司的新app有多语言, 登录注册的UITextField提示语多语言情况下显示不全, 所以需求是提示语多行,输入还是单行
测试提了bug 不得不改啊
思路: UITextField的placeholder 所在的label没有公开, 只能写替代的了
来个继承UITextField的类
1.来个UILabel, 比方叫placeHolderLael., 设置好 textColor, textAlignment, font, 一般placeholder不会太长 numberOfLines设置为2, 防止超级长的显示不了 adjustsFontSizeToFitWidth设置true
2. override 下 placeholder, 在didSet里面 placeHolderLabel.text = placeholder, 然后把固有的 设置clear颜色 attributedPlaceholder = NSAttributedString(string: "", attributes: [NSAttributedString.Key.foregroundColor: UIColor.clear, NSAttributedString.Key.font: UIFont.regularAuto(14)])
3. init里面 addSubview(placeHolderLabel) frame和UITextField设置一致
4. 加一个textDidChangeNotification的通知, 方法里面显示隐藏, 此处注意判断是否是自己.
5. 后台发现 UITextField还要在切换邮箱手机的时候 "复用", override 下 text, 处理隐藏显示
代码如下(代码复制进的编辑里面 变的好惨 有啥技巧吗? ):
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")
}
}