lunes, 13 de noviembre de 2017

iOS: TextView with placeholder text


class TextViewWithPlaceholder: UITextView {
    
    private var _placeholderTextColor: UIColor = UIColor.lightGray
    @IBInspectable var placeholderTextColor: UIColor {
        set {
            _placeholderTextColor = newValue
            textColor = newValue
        }
        get {
            return _placeholderTextColor
        }
    }
    @IBInspectable var placeholderText: String? {
        didSet {
            if text.isEmpty {
                text = placeholderText
            }
        }
    }
    
    private var initialTextColor: UIColor?
    
    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        
        commonInit()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        
        commonInit()
    }
    
    private func commonInit() {
        
        initialTextColor = textColor
        
        text = placeholderText
        
        NotificationCenter.default.addObserver(self, selector: #selector(didBeginEditing(_:)), name: UITextView.textDidBeginEditingNotification, object: self)
        NotificationCenter.default.addObserver(self, selector: #selector(didEndEditing(_:)), name: UITextView.textDidEndEditingNotification, object: self)
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    @objc func didBeginEditing(_ notification: NSNotification) {
        
        if let textView = notification.object as? TextViewWithPlaceholder, textView == self, text == placeholderText {
            
            text = ""
            textColor = initialTextColor
        }
    }
    
    @objc func didEndEditing(_ notification: NSNotification) {
        
        if let textView = notification.object as? TextViewWithPlaceholder, textView == self, text.isEmpty {
            
            text = placeholderText
            textColor = placeholderTextColor
        }
    }
}

No hay comentarios:

Publicar un comentario