let ideaTextView = UITextView()
let placeHolderLabel = UILabel()
placeHolderLabel.text = "写下你的问题或建议,我们将及时跟进解决(建议上传截图帮助我们解决问题,感谢!)"
placeHolderLabel.numberOfLines = 0
placeHolderLabel.font = UIFont.systemFont(ofSize: 15)
placeHolderLabel.textColor = UIColor.lightGray
placeHolderLabel.sizeToFit()
ideaTextView.addSubview(placeHolderLabel)
ideaTextView .setValue(placeHolderLabel, forKeyPath: "_placeholderLabel")
ideaTextView.font = placeHolderLabel.font
或者
class PlaceholderTextView: UITextView {
lazy var placeholderTextView: UITextView = {
let placeholderTextView = UITextView()
placeholderTextView.backgroundColor = .clear
placeholderTextView.textColor = UIColor.itForegroundPlaceholderText
placeholderTextView.isEditable = false
placeholderTextView.isSelectable = false
placeholderTextView.isUserInteractionEnabled = false
placeholderTextView.contentInset = contentInset
placeholderTextView.font = UIFont.itTextRegular
placeholderTextView.inputAccessoryView = inputAccessoryView
return placeholderTextView
}()
var placeholder: String? {
didSet {
if let text = placeholder, text.count > 0 {
placeholderTextView.text = placeholder
addSubview(placeholderTextView)
}
}
}
override func awakeFromNib() {
super.awakeFromNib()
textContainerInset = UIEdgeInsets(top: 16.0, left: 12.0, bottom: 4.0, right: 12.0)
}
override func layoutSubviews() {
super.layoutSubviews()
placeholderTextView.frame = bounds
placeholderTextView.textContainerInset = textContainerInset
}
func updatePlaceholderTextView(text: String?) {
placeholderTextView.isHidden = !(text?.isEmpty ?? true)
}
}
效果如下: