美文网首页
带有placeholder的UITextView

带有placeholder的UITextView

作者: iOS_tree | 来源:发表于2023-06-07 19:34 被阅读0次

监听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
    }

}

相关文章

网友评论

      本文标题:带有placeholder的UITextView

      本文链接:https://www.haomeiwen.com/subject/hhhoedtx.html