Skip to content

Instantly share code, notes, and snippets.

@kobeumut
Created February 10, 2018 19:21
Show Gist options
  • Save kobeumut/4f321b86eee9af039e2015041882d188 to your computer and use it in GitHub Desktop.
Save kobeumut/4f321b86eee9af039e2015041882d188 to your computer and use it in GitHub Desktop.
Add Placeholder Swift 4 - iOS
import UIKit
extension UITextView: UITextViewDelegate {
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
}
}
let textView = UITextView()
textView.placeholder = "Your Messaging..."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment