123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127 |
- import UIKit
- extension UITextView {
- public var isEmpty: Bool {
- return text?.isEmpty ?? false
- }
- public func clear() {
- text = ""
- attributedText = NSAttributedString(string: "")
- }
- }
- private var isLimit = false
- extension UITextView: UITextViewDelegate {
-
- override open var bounds: CGRect {
- didSet {
- resizePlaceholder()
- }
- }
- open override var backgroundColor: UIColor? {
- didSet {
- if let placeholderLabel = viewWithTag(1000001) as? UILabel {
- placeholderLabel.backgroundColor = backgroundColor
- }
- }
- }
- public var placeholder: String? {
- get {
- var placeholderText: String?
- if let placeholderLabel = viewWithTag(1000001) as? UILabel {
- placeholderText = placeholderLabel.text
- }
- return placeholderText
- }
- set {
- if let placeholderLabel = viewWithTag(1000001) as! UILabel? {
- placeholderLabel.text = newValue
- placeholderLabel.sizeToFit()
- } else {
- self.addPlaceholder(newValue!)
- }
- delegate = self
- }
- }
-
-
-
- public func textViewDidChange(_ textView: UITextView) {
- if let placeholderLabel = viewWithTag(1000001) as? UILabel {
- placeholderLabel.isHidden = text.count > 0
- }
-
- var heightConstraint = self.heightAnchor.constraint(equalToConstant: height)
- for constraint in constraints where constraint.firstAttribute == .height {
- heightConstraint = constraint
- }
- let value = max(contentSize.height, heightConstraint.constant)
- heightConstraint.constant = value
- if !heightConstraint.isActive {
- heightConstraint.isActive = true
- }
- }
-
- private func resizePlaceholder() {
- if let placeholderLabel = viewWithTag(1000001) as! UILabel? {
- let labelX = textContainer.lineFragmentPadding + textContainerInset.left
- let labelY = textContainerInset.top - 2
- let labelWidth = frame.width - (labelX * 2)
- let labelHeight = placeholderLabel.frame.height
- placeholderLabel.frame = CGRect(x: labelX, y: labelY, width: labelWidth, height: labelHeight)
- }
- }
-
- private func addPlaceholder(_ placeholderText: String) {
- let placeholderLabel = UILabel()
- placeholderLabel.text = placeholderText
- placeholderLabel.sizeToFit()
- placeholderLabel.font = font
- placeholderLabel.textColor = UIColor.lightGray
- placeholderLabel.tag = 1000001
- placeholderLabel.isHidden = text.count > 0
- addSubview(placeholderLabel)
- resizePlaceholder()
- delegate = self
- }
- }
- extension UITextView {
- public func scrollToBottom() {
- let range = NSRange(location: text.count - 1, length: 1)
- scrollRangeToVisible(range)
- }
- public func scrollToTop() {
- let range = NSRange(location: 0, length: 1)
- scrollRangeToVisible(range)
- }
- }
|