Add placeholder to textView iOS swift || Placeholder for UITextView iOS swift

Solution:

In textfield we had an option for placeholder but it is not available for textView in XCode.No worries don't bang your heads on wall to handle this. I had the solution go ahead and enjoy.

First you have to create a label and add it to textview if textView is empty then show the label.


    var placeholderLabel : UILabel!



In viewdidload add the below code


        self.addPlaceHolderToTextView()

            placeholderLabel.isHidden = !textTV.text.isEmpty

Also add the below function in your class.

    // MARK: - PlaceHolders
    func addPlaceHolderToTextView(){
        placeholderLabel = UILabel()
        placeholderLabel.text = "Enter text"
        placeholderLabel.font = UIFont.systemFont(ofSize: (textTV.font?.pointSize)!) 
        placeholderLabel.sizeToFit()
        textTV.addSubview(placeholderLabel)
        placeholderLabel.frame.origin = CGPoint(x:5 , y: (textTV.font?.pointSize)! / 2 )
        placeholderLabel.textColor = UIColor(white: 0, alpha: 0.3)
        placeholderLabel.isHidden = !textTV.text.isEmpty
    }


In textview delegate method add the below code.Because if you edit the textview at runtime it will works.


 // MARK: - TtextView delegates
    func textViewDidChange(_ textView: UITextView) {
        placeholderLabel.isHidden = !textView.text.isEmpty
    }



That's it enjoyyyy.....

Comments

Popular posts from this blog

Invalid bundle error while upload the app to the app Store

Convert NsNumber, NSDate to String in iOS Swift

Global LocationManager Singleton class iOS Swift