监听UITextView的text变化来进行显示隐藏PlaceholderLabel
class PlaceholderTextView: UITextView, UITextViewDelegate {
var contentdelegate:UITextViewDelegate?
// MARK: Properties
private let placeholderLabel = UILabel()
var placeholder: String? {
get {
return placeholderLabel.text
}
set {
placeholderLabel.text = newValue
setNeedsLayout()
}
}
override var text: String! {
didSet {
updatePlaceholderVisibility()
}
}
override var attributedText: NSAttributedString! {
didSet {
updatePlaceholderVisibility()
}
}
// MARK: Initialization
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupPlaceholderLabel()
}
override init(frame: CGRect, textContainer: NSTextContainer?) {
super.init(frame: frame, textContainer: textContainer)
setupPlaceholderLabel()
self.delegate = self
}
// MARK: Layout
override func layoutSubviews() {
super.layoutSubviews()
placeholderLabel.sizeToFit()
placeholderLabel.frame.origin = CGPoint(x: textContainerInset.left + 5, y: textContainerInset.top)
}
func textViewDidChange(_ textView: UITextView) {
self.contentdelegate?.textViewDidChange?(self)
updatePlaceholderVisibility()
}
// MARK: Helpers
private func setupPlaceholderLabel() {
placeholderLabel.textColor = .gray
placeholderLabel.font = UIFont.systemFont(ofSize: 16)
placeholderLabel.numberOfLines = 0
addSubview(placeholderLabel)
updatePlaceholderVisibility()
}
private func updatePlaceholderVisibility() {
placeholderLabel.isHidden = !text.isEmpty
}
}
网友评论