Swift UITextView placeholder
2023-06-20 本文已影响0人
YourSummer
网上有多种给UITextview添加占位字符的方案, 我最喜欢这一种:
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 ?? ""
}
}
}
示例:
let textView = UITextView()
textView.placeholder = "请给个小心心"