網(wǎng)上有多種給UITextview添加占位字符的方案, 我最喜歡這一種:
感謝@瘋狂超人_
針對(duì)這一問(wèn)題, 已做如下修改, 請(qǐng)使用第二種改進(jìn)方案
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. 改進(jìn)方案
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 = "請(qǐng)給個(gè)小心心"