网上有多种给UITextview添加占位字符的方案, 我最喜欢这一种:
感谢@疯狂超人_
针对这一问题, 已做如下修改, 请使用第二种改进方案
1. 原方案
import UIKit
extension UITextView {
var placeholder: String {
set {
let lb = UILabel()
lb.font = font
lb.numberOfLines = 0
lb.textColor = .lightGray
lb.text = newValue
addSubview(lb)
setValue(lb, forKey: "_placeholderLabel")
}
get {
let lb = value(forKey: "_placeholderLabel") as? UILabel
return lb?.text ?? ""
}
}
}
2. 改进方案
import UIKit
extension UITextView {
private static let kPlaceholderTag = 20240202
var placeholder: String {
set {
if let lb = viewWithTag(UITextView.kPlaceholderTag) as? UILabel {
lb.text = newValue
} else {
let lb = UILabel()
lb.tag = UITextView.kPlaceholderTag
lb.font = font
lb.numberOfLines = 0
lb.textColor = .lightGray
lb.text = newValue
addSubview(lb)
setValue(lb, forKey: "_placeholderLabel")
}
}
get {
let lb = value(forKey: "_placeholderLabel") as? UILabel
return lb?.text ?? ""
}
}
}
示例:
let textView = UITextView()
textView.placeholder = "请给个小心心"