UITextField通过attributedPlaceholder修改占位符的字体的大小后,不再居中显示了,怎么处理呢?记录一下解决的办法,下次可直接使用!
extension UITextField { class func make(_ superView: UIView, tip: String, constraints: HYBConstraintClosure?) ->UITextField { let txt = UITextField() txt.placeholder = tip let fontSize: CGFloat = 13.0 txt.font = UIFont.systemFont(ofSize: fontSize) let style = NSMutableParagraphStyle() style.minimumLineHeight = (txt.font?.lineHeight)! - ((txt.font?.lineHeight)! - UIFont.systemFont(ofSize: fontSize).lineHeight) / 2.0; let attr = NSMutableAttributedString(string: tip, attributes: [ NSFontAttributeName: UIFont.systemFont(ofSize: fontSize), NSParagraphStyleAttributeName: style ]) txt.attributedPlaceholder = attr superView.addSubview(txt) txt.autocorrectionType = .no txt.autocapitalizationType = .none txt.leftViewMode = .always txt.leftView = UIView(frame: r(0.0, 0.0, 8.0, 1.0)) txt.clearButtonMode = .always if let c = constraints { txt.snp.makeConstraints(c) } return txt } }
其中的关键在于重新计算出最小高度,用于校正,从而实现垂直居中!下面的代码是关键!
style.minimumLineHeight = (txt.font?.lineHeight)! - ((txt.font?.lineHeight)! - UIFont.systemFont(ofSize: fontSize).lineHeight) / 2.0;
承接:ThinkPHP项目开发、网站项目开发、微信项目开发、微信小程序项目开发、App开发,欢迎联系标哥QQ632840804