轻松让UITextView实现placeholder, 不需要一系列的隐藏显示逻辑。
placeholder.gif
-
在UITextView extension中新建一个设置placeholder的方法
import UIKit
extension UITextView {
func setPlaceholder(text: String) {
let placeholderLabel = UILabel()
placeholderLabel.numberOfLines = 0
placeholderLabel.font = font
placeholderLabel.textColor = UIColor(white: 120/255, alpha: 1)
placeholderLabel.text = text
placeholderLabel.sizeToFit()
addSubview(placeholderLabel)
setValue(placeholderLabel, forKeyPath: "_placeholderLabel")
}
}
我的理解是,Apple把“_placeholderLabel”这个key预留了。
-
使用UITextView, 调用setPlaceholder()给placeholder赋值
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
setupTextView()
}
private func setupTextView() {
let textView = UITextView()
textView.font = UIFont.systemFont(ofSize: 20.0)
textView.layer.borderColor = UIColor(white: 229/255, alpha: 1).cgColor
textView.layer.borderWidth = 1.0
textView.layer.masksToBounds = true
textView.textContainer.lineFragmentPadding = 15.0
textView.setPlaceholder(text: "请输入你想说的话。")
view.addSubview(textView)
textView.translatesAutoresizingMaskIntoConstraints = false
textView.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 20.0).isActive = true
textView.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -20.0).isActive = true
textView.topAnchor.constraint(equalTo: view.topAnchor, constant: 100.0).isActive = true
textView.heightAnchor.constraint(equalToConstant: 200.0).isActive = true
}
}
不需要在UITextView delegate或者给UITextView text赋值时候做隐藏显示等逻辑处理了。