美文网首页技术笔记
解决:UITextfield 无法修改 placeholder

解决:UITextfield 无法修改 placeholder

作者: o本是后山人o偶作前堂客o | 来源:发表于2017-07-24 10:32 被阅读15次

    前几天遇到一个问题:UITextfield 这个控件的属性placeholder 的字体大小无法修改.  

    网上的2种方法:一般只能修改掉 颜色,而对字体无效.

    1

    [textFieldsetValue:[UIColor redColor]forKeyPath:@"_placeholderLabel.textColor"];  [textFieldsetValue:[UIFontboldSystemFontOfSize:16]forKeyPath:@"_placeholderLabel.font"];

    2  在iOS6.0之后提供的attributedPlaceholder属性:

    [placeholder addAttribute:NSForegroundColorAttributeNamevalue:[UIColorredColor]              range:NSMakeRange(0, holderText.length)];

    [placeholder addAttribute:NSFontAttributeNamevalue:[UIFontboldSystemFontOfSize:16]              range:NSMakeRange(0, holderText.length)];textField.attributedPlaceholder = placeholder;[cell.contentView addSubview:textField];

    这 2种方法:一般只能修改掉 颜色,而对字体无效.

    于是 写一个自己的 placeholder label属性.进行解决这个问题.


    class MyTextField:UITextField {

    private var _myPlaceHolderLabel = UILabel()

    var myPlaceHolderLabel : UILabel {

    get {

    return _myPlaceHolderLabel

    }

    }

    override init(frame: CGRect) {

    super.init(frame: frame)

    _myPlaceHolderLabel.text = text

    _myPlaceHolderLabel.numberOfLines = 0;

    _myPlaceHolderLabel.textColor = UIColor.lightGray

    _myPlaceHolderLabel.sizeToFit()

    self.addSubview(_myPlaceHolderLabel)

    _myPlaceHolderLabel.font = UIFont.boldSystemFont(ofSize: 13)

    _myPlaceHolderLabel.snp.makeConstraints { (make) in

    make.top.bottom.left.right.equalToSuperview()

    }

    NotificationCenter.default.addObserver(self, selector: #selector(MyTextField.textFieldDidChange), name: NSNotification.Name.UITextFieldTextDidChange, object: self)

    }

    required init?(coder aDecoder: NSCoder) {

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

    }

    func textFieldDidChange(hidePlaceHolder:Bool) {

    if (self.text?.characters.count)! > 0 || hidePlaceHolder{

    _myPlaceHolderLabel.isHidden = true

    }else {

    _myPlaceHolderLabel.isHidden = false

    }

    }

    }

    相关文章

      网友评论

        本文标题:解决:UITextfield 无法修改 placeholder

        本文链接:https://www.haomeiwen.com/subject/gqnvkxtx.html