Add Placeholder To UITextView in Swift 4 - iOS - Swift 4 Tutorials W3Schools

Hot

Post Top Ad

30 Oct 2017

Add Placeholder To UITextView in Swift 4 - iOS

Swift provides default placeholder property to UITextField but not to UITextView.

So if you need a multi-line editable text view, you don’t get a pretty placeholder. Here you will learn how to add placeholder text to UItextView.


Here we will show step by step:

Step 1:

Firstly create new swift file and name it TextViewPlaceholder.swift and save it.

Next import UIKit and create extension to UITextView as follow:

import UIKit

extension UITextView: UITextViewDelegate {
// Code
}

Step 2:

Here we are going to add label as subview in order to show placeholder text. No worries it's quite simple.

Add the following code inside the extension:

override open var bounds: CGRect {
    didSet {
        self.resizePlaceholder()
    }
}

public var placeholder: String? {
    get {
        var placeholderText: String?
        
        if let placeholderLbl = self.viewWithTag(50) as? UILabel {
            placeholderText = placeholderLbl.text
        }
        
        return placeholderText
    }
    set {
        if let placeholderLbl = self.viewWithTag(50) as! UILabel? {
            placeholderLbl.text = newValue
            placeholderLbl.sizeToFit()
        } else {
            self.addPlaceholder(newValue!)
        }
    }
}

public func textViewDidChange(_ textView: UITextView) {
    if let placeholderLbl = self.viewWithTag(50) as? UILabel {
        placeholderLbl.isHidden = self.text.characters.count > 0
    }
}

private func resizePlaceholder() {
    if let placeholderLbl = self.viewWithTag(50) as! UILabel? {
        let x = self.textContainer.lineFragmentPadding
        let y = self.textContainerInset.top - 2
        let width = self.frame.width - (x * 2)
        let height = placeholderLbl.frame.height
        
        placeholderLbl.frame = CGRect(x: x, y: y, width: width, height: height)
    }
}

private func addPlaceholder(_ placeholderText: String) {
    let placeholderLbl = UILabel()
    
    placeholderLbl.text = placeholderText
    placeholderLbl.sizeToFit()
    
    placeholderLbl.font = self.font
    placeholderLbl.textColor = UIColor.lightGray
    placeholderLbl.tag = 50
    
    placeholderLbl.isHidden = self.text.characters.count > 0
    
    self.addSubview(placeholderLbl)
    self.resizePlaceholder()
    self.delegate = self
}

Above code will work in both orientations.

Step 3:

Here we will show how to use.

Simply add placeholder to UITextView as below:

let textView = UITextView()
textView.placeholder = "Start typing here"


Get the full code here.

No comments:

Post a Comment

Post Top Ad