-1

My scenario, I am trying to create UITextView with a custom Placeholder by using below code, But whenever I clicked into UITextview my Placeholder not hide. How to fix this?

My Code Below

In ViewDidLoad

  myTextview.delegate = self

  self.myTextview.text = "Enter Comments"
            self.myTextview.textColor = UIColor .lightGray

Added below two UITextView Delegates

func textViewDidBeginEditing(_ textView: UITextView) {
        if myTextview.textColor == UIColor.lightGray {
            myTextview.text = nil
            myTextview.textColor = UIColor.black
        }
    }

    func textViewDidEndEditing(_ textView: UITextView) {
        if myTextview.text.isEmpty {
            myTextview.text = "Enter Comments"
            myTextview.textColor = UIColor.lightGray
        }
    }
Ben Dev
  • 77
  • 1
  • 12

3 Answers3

1

Hello i have same issue and i got solution like below i hope its work for you

Below is my code

CODE

var placeholderLabel : UILabel!

PUT This Code inside your viewDidLoad()

yourTextView.delegate = self
placeholderLabel = UILabel()
placeholderLabel.text = "Your Place Holder Text"
placeholderLabel.font = UIFont.italicSystemFont(ofSize: (yourTextView.font?.pointSize)!)
placeholderLabel.sizeToFit()
yourTextView.addSubview(placeholderLabel)
placeholderLabel1.frame.origin = CGPoint(x: 5, y: (yourTextView.font?.pointSize)! / 2)
placeholderLabel.textColor = UIColor.lightGray
placeholderLabel.isHidden = !yourTextView.text.isEmpty

then inside your textViewDidChange write below code

func textViewDidChange(_ textView: UITextView) {
        placeholderLabel.isHidden = !yourTextView.text.isEmpty
}

please try with this and tell me your problem is solved or not

Vishal Parmar
  • 615
  • 4
  • 31
0

Working below code for UITextView Placeholder.

The actual question and Its solution.

Whenever user click the UITextView the placeholder should visible also If user enter anything text inside UITextView, Then the placeholder should hide and allow to show a user typing text. But the problem is not hiding placeholder whenever user enable to type.

It should work like a TextField Placeholder. Below code helping me to fix my issue.

import UIKit

class PlaceholderTextView: UITextView {

    @IBInspectable var placeholderColor: UIColor = UIColor.lightGray
    @IBInspectable var placeholderText: String = ""

    override var font: UIFont? {
        didSet {
            setNeedsDisplay()
        }
    }

    override var contentInset: UIEdgeInsets {
        didSet {
            setNeedsDisplay()
        }
    }

    override var textAlignment: NSTextAlignment {
        didSet {
            setNeedsDisplay()
        }
    }

    override var text: String? {
        didSet {
            setNeedsDisplay()
        }
    }

    override var attributedText: NSAttributedString? {
        didSet {
            setNeedsDisplay()
        }
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setUp()
    }

    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
    }

    private func setUp() {
        NotificationCenter.default.addObserver(self,
                                               selector: #selector(self.textChanged(notification:)),
                                               name: Notification.Name("UITextViewTextDidChangeNotification"),
                                               object: nil)
    }

    @objc func textChanged(notification: NSNotification) {
        setNeedsDisplay()
    }

    func placeholderRectForBounds(bounds: CGRect) -> CGRect {
        var x = contentInset.left + 4.0
        var y = contentInset.top  + 9.0
        let w = frame.size.width - contentInset.left - contentInset.right - 16.0
        let h = frame.size.height - contentInset.top - contentInset.bottom - 16.0

        if let style = self.typingAttributes[NSAttributedString.Key.paragraphStyle] as? NSParagraphStyle {
            x += style.headIndent
            y += style.firstLineHeadIndent
        }
        return CGRect(x: x, y: y, width: w, height: h)
    }

    override func draw(_ rect: CGRect) {
        guard let text = self.text,
            let font = self.font else {
                return
        }

        let fontKey = NSAttributedString.Key(rawValue: NSAttributedString.Key.font.rawValue)
        let colorKey = NSAttributedString.Key(rawValue: NSAttributedString.Key.foregroundColor.rawValue)
        let paragraphKey = NSAttributedString.Key(rawValue: NSAttributedString.Key.paragraphStyle.rawValue)
        if text.isEmpty && !placeholderText.isEmpty {
            let paragraphStyle = NSMutableParagraphStyle()
            paragraphStyle.alignment = textAlignment
            let attributes: [NSAttributedString.Key: Any] = [
                fontKey: font,
                colorKey: placeholderColor,
                paragraphKey: paragraphStyle]

            placeholderText.draw(in: placeholderRectForBounds(bounds: bounds), withAttributes: attributes)
        }
        super.draw(rect)
    }
}
Ben Dev
  • 77
  • 1
  • 12
  • Your updated answer doesn't explain what was wrong with the code in your question. – rmaddy Aug 07 '19 at 07:45
  • @rmaddy In my question which I mentioned that code not hiding Placeholder after typing text into UITextView. I don't know what else I need to explain for you buddy. :) – Ben Dev Aug 07 '19 at 08:50
  • Your answer should explain *why* your original code wasn't working. – rmaddy Aug 07 '19 at 16:14
-7

Change your code to

func textViewDidBeginEditing(_ textView: UITextView) {
    if myTextview.text == "Enter Comments" {
        myTextview.text = ""
        myTextview.textColor = UIColor.black
    }
}

func textViewDidEndEditing(_ textView: UITextView) {
    if myTextview.text == "" {
        myTextview.text = "Enter Comments"
        myTextview.textColor = UIColor.lightGray
    }
}
Vinu Jacob
  • 393
  • 2
  • 15
  • The OP has made it clear that `textViewDidBeginEditing` isn't being called. So changing what it does doesn't fix anything. – rmaddy Aug 07 '19 at 06:21
  • @rmaddy We cannot check equality of color. He is trying to check the color in the if condition. – Vinu Jacob Aug 07 '19 at 06:24
  • But the method isn't be called so the `if` statement is irrelevant at this point. – rmaddy Aug 07 '19 at 06:25
  • I am trying to explain the logic of code he is using in the delegate method. – Vinu Jacob Aug 07 '19 at 06:27
  • You are missing the point. `textViewDidBeginEditing` is not being called. The code inside it currently irrelevant. Your answer makes no attempt to solve the problem of the delegate method not being called at all. – rmaddy Aug 07 '19 at 06:33
  • in his question, he is saying that the placeholder is not hiding. Not the method is not getting invoked. – Vinu Jacob Aug 07 '19 at 06:37
  • You need to read the comments below the question where the OP stated that it's not being called. – rmaddy Aug 07 '19 at 06:38
  • I posted my answer before the comments added in his question. – Vinu Jacob Aug 07 '19 at 06:39
  • And after posting my answer only he updated his question. – Vinu Jacob Aug 07 '19 at 06:39
  • And you need to update your answer based on the new information. That's a risk you take when you post an answer too quickly without all of the relevant information. – rmaddy Aug 07 '19 at 06:40
  • I post the answer based on the codes he mention in the question. – Vinu Jacob Aug 07 '19 at 06:42